這幾天麥子有在整理關(guān)于Open Graph元數(shù)據(jù)的標(biāo)簽信息,看到有不少網(wǎng)友認(rèn)為這個(gè)對(duì)于SEO效果很多,但是從策略上講,趨勢(shì)對(duì)于谷歌的優(yōu)化是有一些幫助的,畢竟也算是一個(gè)協(xié)議內(nèi)容。我們可以使用Yoast SEO插件實(shí)現(xiàn),但是如果我們不用插件如何實(shí)現(xiàn)呢?在之前的文章中,我們簡(jiǎn)單的介紹OG的信息標(biāo)簽的一些功能。
在這里,整理來(lái)自國(guó)外一個(gè)網(wǎng)站的非插件實(shí)現(xiàn)的方法,這里先記錄下來(lái),后面有用到的時(shí)候在基礎(chǔ)上修改。
<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; }
這里是 用來(lái)獲取縮略圖的函數(shù)定義放到 Functions.php中。如果沒有圖我們可以設(shè)定一個(gè)默認(rèn)圖,比如LOGO。
具體不同的主題兼容性不同,我們需要看看實(shí)際的代碼變化再調(diào)整。
參考地址:https://mercytapscott.com/insert-open-graph-tags-wordpress-theme-without-plugin/
評(píng)論