Created
January 28, 2018 19:23
-
-
Save andykillen/9c781e5332f32e01da6a2ea3689caeeb to your computer and use it in GitHub Desktop.
Show an image to facebook, but show a full page to users
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Template Name: Facebook sees the image | |
* | |
**/ | |
/** | |
* Force no caching, just in case you have some fancy varnish, load balancer | |
* or other things | |
**/ | |
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); | |
header("Cache-Control: post-check=0, pre-check=0", false); | |
header("Pragma: no-cache"); | |
function show_image_to_facebook(){ | |
// set default value | |
$redirect = true; | |
// Check for facebook bots | |
$pattern = '/(FacebookExternalHit|visionutils|Facebot)/i'; | |
$agent = filter_input(INPUT_SERVER, 'HTTP_USER_AGENT', FILTER_SANITIZE_ENCODED); | |
if(preg_match($pattern,$agent)){ | |
$redirect = false; | |
} | |
// exit early if not facebook | |
if($redirect){ | |
return; | |
} | |
// get the post ID outside the loop | |
global $wp_query; | |
$id = $wp_query->post->ID; | |
// get the image url | |
$url = get_the_post_thumbnail_url($id, 'gif_image'); | |
// get the image path | |
$path = parse_url($url, PHP_URL_PATH); | |
// check if the file exists, and exit if it is not found | |
if(!file_exists($path)){ | |
return; | |
} | |
// set the mime type of the file so it displays properly | |
header("content-type: " . mime_content_type($path)); | |
// output the image | |
readfile($path); | |
// stop all processing as facebook is complete | |
exit; | |
} | |
// Try to show image to facebook if it this is a facebook bot and the file exists | |
show_image_to_facebook(); | |
get_header(); | |
if ( have_posts() ) { | |
while ( have_posts() ) { | |
the_post(); | |
// | |
// Post Content here | |
// | |
} // end while | |
} // end if | |
get_footer(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment