Skip to content

Instantly share code, notes, and snippets.

@andrewspear
Last active July 6, 2017 08:10
Show Gist options
  • 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);
}
?>
@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