With the help of Facebook rest API, we can create a Facebook feed on our website. A Facebook feed on the website may help to boost business.
In this article, I’ll show how to get data from a Facebook page.
For fetching data from Facebook you need two things:
1. Page ID
2. Access Token
Facebook provides some endpoints to access data. But for authentication, you need those two pieces of information.
$page_id = 'your facebook page id'; $token = 'your access token'; $url = 'https://graph.facebook.com/v4.0/' . $page_id . '/posts?' . '&access_token=' . $token; $fb_posts = wp_remote_get( $url ); $posts = wp_remote_retrieve_body( $fb_posts ); print_r( json_decode( $posts ) );
Now You are getting data but only basic data. For making a feed you need more depth information right?
You can also add query parameters in the endpoint.
$url_queries = 'fields=status_type,created_time,from,message,story,full_picture,permalink_url,attachments.limit(1){type,media_type,title,description,unshimmed_url},comments.summary(total_count),reactions.summary(total_count)'; $page_id = 'your facebook page id'; $token = 'your access token'; $url = 'https://graph.facebook.com/v4.0/' . $page_id . '/posts?' . $url_queries . '&access_token=' . $token; $fb_posts = wp_remote_get( $url ); $posts = wp_remote_retrieve_body( $fb_posts ); print_r( json_decode( $posts ) );
Now with some HTML and CSS, you can make a pretty visualization of the feed.
Congratulations, you have created the feed. But it’s not good for performance. Because at every page refresh it’ll fetch data from a Facebook database, which is time-consuming.
So, you need to cash your data for better performance. WordPress has a mechanism called transient. It used to cash data for a certain period of time.
At line 8, it checks if the transient is not set, then fetches data from the endpoint and sets the transient for 5 minutes. Otherwise, get cached data from line 1, get_transient
Reference:
wp_remote_get
wp_remote_retrieve_body
get_transient
set_transient
Facebook Page API