Force Facebook to use the featured image automatically


Here you will find a function that performs the process that we mentioned previously regarding solving the problem of images of topics when participating in Facebook automatically without the need to visit the Facebook tool for revision. This process only requires you to update this topic for old topics, but when you will publish a new topic, the process will take place immediately after publicationThe function to update the featured image of the article on Facebook has been updated and a code to empty the cache in case you are using the w3 total cache or wp super cache add-on

The function is pasted into functions.php or functions-custom.php

1/*
2* Function Description : Facebook Scrape
3* Author Name : Mouad Achemli
4* Source : https://www.mwordpress.net/force-facebook-to-update-post-thumbnail-automatically/
5* Inspered from : https://stackoverflow.com/a/32916433/2535061
6* @website : https://www.mwordpress.net/
7*
8*/
9function scrape_open_graph($post) {
10
11global $pagenow;
12global $post;
13
14// Flush W3 Total Cache
15if (function_exists(‘w3tc_pgcache_flush_post’)) :
16w3tc_pgcache_flush_post($post->ID);
17endif;
18
19// Flush WP Super Cache
20if (function_exists(‘wp_cache_post_change’)) :
21wp_cache_post_change($post->ID);
22endif;
23
24// get key
25$check_key = get_post_meta($post->ID, ‘opengraph-is-update’ , true);
26if (!empty($check_key)) {
27// Nothing to do
28} else {
29// add meta key value for next check
30add_post_meta($post->ID, ‘opengraph-is-update’, ‘yes’, true );
31// Facebook scrape
32$url = ‘https://graph.facebook.com’;
33$param = array(
34‘id’ => get_permalink( $post->ID ),
35‘scrape’ => ‘true’,
36‘method’ => ‘post’
37);
38wp_remote_get(add_query_arg( $param, $url ));
39
40}
41
42}
43add_action(‘publish_post’, ‘scrape_open_graph’);
44add_action(‘save_post’, ‘scrape_open_graph’);

When you update the article from the edit page, you will find that a field named ‘opengraph-is-update’ has been added as follows:

opengraph is update - WordPress Magazine

If you change the featured image of the article and want it to be used by Facebook, delete the field indicated in the image above.

Peace, mercy and blessings of God

Leave a Comment