自定义分享WordPress到Facebook的内容(Open Graph Protocol)

以下代码段是加入wordpress主题中的header.php文件中的。也可以用于非WordPress,目的是在head里面加入社交分享可以识别的meta标签。

同时有个调试工具的链接:https://developers.facebook.com/tools/debug/sharing 。更新了meta之后,要去这个网站同样更新一下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
  $thumb = get_post_meta($post->ID,'_thumbnail_id',false);
  $thumb = wp_get_attachment_image_src($thumb[0], false);
  $thumb = $thumb[0];
  $default_img = get_bloginfo('stylesheet_directory').'/images/default_icon.jpg';
?>
<?php if(is_single() || is_page()) { ?>
<meta property="og:type" content="article" />
<meta property="og:title" content="<?php single_post_title(''); ?>" />
<meta property="og:description" content="<?php
$out_excerpt = str_replace(array("\r\n", "\r", "\n"), "", get_the_excerpt());
echo apply_filters('the_excerpt_rss', 
$out_excerpt);
?>" />
<meta property="og:url" content="<?php the_permalink(); ?>"/>
<meta property="og:image" content="<?php if ( $thumb[0] == null ) { echo $default_img; } else { echo $thumb; } ?>" />
<?php  } else { ?>
<meta property="og:type" content="article" />
<meta property="og:title" content="<?php bloginfo('name'); ?>" />
<meta property="og:url" content="<?php bloginfo('url'); ?>"/>
<meta property="og:description" content="<?php bloginfo('description'); ?>" />
    <meta property="og:image" content="<?php  if ( $thumb[0] == null ) { echo $default_img; } else { echo $thumb; } ?>" />
<?php  }  ?>
文章目录
,