Wordpress主题添加ogp协议meta标签

Wordpress主题添加ogp协议meta标签

OGP(The Open Graph protocol)协议是一种新的HTTP头部标记,即Open Graph Protocol,即这种协议可以让网页成为一个“富媒体对象”。由于现在社交类网站大行其道,在HTML头部添加引用此类协议标注有助于被社交网站识别。

OG协议META标签

  • og:title 标题
  • og:type 类型
  • og:image 略缩图地址
  • og:url 页面地址
  • og:description 页面的简单描述
  • og:site_name 页面所在网站名
  • og:videosrc 视频或者Flash地址
  • og:audiosrc 音频地址

一般的,可以在wordpress 文件header.php<?php wp_head(); ?>前加入以下内容

<meta property="og:title" content="<?php the_title();?>" />
<meta property="og:site_name " content="<?php bloginfo('name'); ?>" />
<?php if (is_single()) : ?>
<meta property="og:type" content="acticle" />
<meta property="og:description" content="<?php echo get_post_excerpt(); ?>" />
<meta property="og:url" content="<?php the_permalink();?>"/> 
<?php if ( has_post_thumbnail()):
  $meta_image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'thumbnail'); ?>
<meta property="og:image" content="<?php echo $meta_image_url[0];?>" />
<?php endif; ?>
<?php else: ?>
<meta property="og:type" content="website" />
<?php endif; ?>

因为要在LOOP循环外获取文章摘要,所以自定了一个function get_post_excerpt() 在文件 functions.php 中:

function get_post_excerpt($post, $excerpt_length=140){
    if(!$post) $post = get_post();
    $post_excerpt = $post->post_excerpt;
    if($post_excerpt == ''){
        $post_content = $post->post_content;
        $post_content = do_shortcode($post_content);
        $post_content = wp_strip_all_tags( $post_content );
        $post_excerpt = mb_strimwidth($post_content,0,$excerpt_length,'…','utf-8');
    }
    $post_excerpt = wp_strip_all_tags( $post_excerpt );
    $post_excerpt = trim( preg_replace( "/[\n\r\t ]+/", ' ', $post_excerpt ), ' ' );
    return $post_excerpt;
}
Y Cheung

Y Cheung

Blogger, Programer & Traveler.
Shanghai