WordPress无插件代码实现Open Graph元数据

这几天麦子有在整理关于Open Graph元数据的标签信息,看到有不少网友认为这个对于SEO效果很多,但是从策略上讲,趋势对于谷歌的优化是有一些帮助的,毕竟也算是一个协议内容。我们可以使用Yoast SEO插件实现,但是如果我们不用插件如何实现呢?在之前的文章中,我们简单的介绍OG的信息标签的一些功能。

在这里,整理来自国外一个网站的非插件实现的方法,这里先记录下来,后面有用到的时候在基础上修改。

<meta property="og:title" content="<?php the_title(); ?>"/>
<meta property="og:type" content="<?php if (is_single() || is_page()) { echo 'article'; } else { echo 'website';} ?>"/>
<meta property="og:image" content="<?php echo get_fbimg(); ?>"/>
<meta property="og:url" content="<?php the_permalink(); ?>"/>
<meta property="og:description" content="<?php echo get_post_meta($post->ID, '_yoast_wpseo_metadesc', true); ?>"/> 
<meta property="og:site_name" content="<?php bloginfo('name'); ?>"/>

我们需要将代码放到头部文件中。

add_filter('language_attributes', 'add_og_xml_ns');
function add_og_xml_ns($content) {
  return ' xmlns:og="http://ogp.me/ns#" ' . $content;
}

add_filter('language_attributes', 'add_fb_xml_ns');
function add_fb_xml_ns($content) {
  return ' xmlns:fb="https://www.facebook.com/2008/fbml" ' . $content;
}

function get_fbimg() {
	$src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), '', '' );
		if ( has_post_thumbnail($post->ID) ) {
		$fbimage = $src[0];
		} else {
			global $post, $posts;
			$fbimage = '';
			$output = preg_match_all('/<img[^>]+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
      if(isset($matches[1][0]) ){
          $fbimage = $matches[1][0];
      } else {
        return false;
      }
	  return $fbimage;
		}
		if(empty($fbimage)) {
		$fbimage = "http://www.yourdomain.com/path-to-your-image/your-fallback-default-image.jpg";
		}
	return $fbimage;
}

这里是 用来获取缩略图的函数定义放到 Functions.php中。如果没有图我们可以设定一个默认图,比如LOGO。

具体不同的主题兼容性不同,我们需要看看实际的代码变化再调整。

参考地址:https://mercytapscott.com/insert-open-graph-tags-wordpress-theme-without-plugin/

投票 post
© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享