Skip to content

Instantly share code, notes, and snippets.

@andrewspear
Last active July 6, 2017 08:10
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save andrewspear/3d9015b1c1d652b4a862 to your computer and use it in GitHub Desktop.
Save andrewspear/3d9015b1c1d652b4a862 to your computer and use it in GitHub Desktop.
Wordpress function to force Facebook to refresh it's cache as a scheduled post
<?
// Ping Facebook with (via a POST request) to refresh the cache (scrape) for a scheduled post as it is published
// Relevant docs: https://developers.facebook.com/docs/opengraph/using-objects#selfhosted-update
// Place this in your Wordpress functions.php file
add_action('transition_post_status', 'purge_future_post', 10, 3);
function purge_future_post($new_status, $old_status, $post) {
if($new_status == 'publish') {
purge_facebook_cache($post);
}
}
function purge_facebook_cache($post_id) {
$fbUrl = 'https://graph.facebook.com';
$pageUrl = get_permalink($post_id);
$fields = array(
'id' => urlencode($pageUrl),
'scrape' => true
);
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$fbUrl);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
$result = curl_exec($ch);
curl_close($ch);
}
?>
@coltjones
Copy link

Not sure how this code would run as expected.
Line 19: $url is not set before it is used.
Line 25: $postUrl is not set before it is used.
Also its good practice to curl_close($ch) when you're done.
Since it's an https address we should probably toss in a curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); too.

Edit: Added CURLOPT_SSL_VERIFYPEER suggestion.

@andrewspear
Copy link
Author

@coltjones Oops, yes, I had a tangle of vars there, $url and $postUrl were supposed to be $pageUrl and $fbUrl respectively. I've updated the code now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment