Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gambolputty/db427d24341f61040bdde1c74a56e1ad to your computer and use it in GitHub Desktop.
Save gambolputty/db427d24341f61040bdde1c74a56e1ad to your computer and use it in GitHub Desktop.
Create custom post & pages output for facebook- & twitter crawlers. Useful for single page application themes built with VueJS oder Angular (facebook crawler doesn't read JavaScript)
function wp_crawler_version() {
if ( !is_admin() ) {
if ( is_home() ) {
return;
}
/*
Get user agent
*/
if ( !isset($_SERVER["HTTP_USER_AGENT"]) )
return;
$agent = $_SERVER["HTTP_USER_AGENT"];
// detect fb crawler: https://developers.facebook.com/docs/sharing/webmasters/crawler
if ( preg_match("/^facebookexternalhit\/1\.1|^facebot|^twitterbot/i", $agent) ) {
if ( is_page() || is_single() ) {
global $post;
$result = [];
$result['title'] = $post->post_title;
$result['excerpt'] = my_excerpt($post->content, $post->post_excerpt);
$result['url'] = $post->guid;
// Advanced Custom Fields plugin
$img_field = get_field('small_img', $post->ID);
if (!empty($img_field)) {
$result['img'] = $img_field['url'];
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php bloginfo('name'); ?> | <?php echo $result['title']; ?></title>
<meta name="description" content="<?php echo $result['excerpt']; ?>">
<meta property="og:title" content="<?php echo $result['title']; ?>" />
<meta property="og:type" content="article" />
<meta property="og:url" content="<?php echo $result['url']; ?>" />
<meta property="og:description" content="<?php echo $result['excerpt']; ?>" />
<meta property="og:site_name" content="<?php bloginfo('name'); ?>" />
<?php if (isset($result['img'])): ?>
<meta property="og:image" content="<?php echo $result['img']; ?>" />
<?php else: ?>
<meta property="og:image" content="<?php echo get_template_directory_uri(); ?>/img/fb_image.png" />
<?php endif; ?>
</head>
<body></body>
</html>
<?php
exit;
}
}
}
}
add_action( 'wp', 'wp_crawler_version' );
function my_excerpt($text, $excerpt){
/*
Derived from Wordpress version 3.0.4
*/
if ($excerpt) return $excerpt;
$text = strip_shortcodes( $text );
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]&gt;', $text);
$text = strip_tags($text);
$text = str_replace("\"", "'", $text);
$excerpt_length = apply_filters('excerpt_length', 55);
$excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
$words = preg_split("/[\n
]+/", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);
if ( count($words) > $excerpt_length ) {
array_pop($words);
$text = implode(' ', $words);
$text = $text . $excerpt_more;
} else {
$text = implode(' ', $words);
}
return apply_filters('wp_trim_excerpt', $text, $excerpt);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment