利用wp_head函数案例实现头部添加Open Graph协议

今天本来是要了解到WordPress函数中哪个是用来添加头部文件的的,这里有了解到是用 wp_head(),这里正好可以示范最近在研究的Open Graph协议。我们要知道,Open Graph协议是比较重要的在谷歌等搜索引擎可以提高搜索引擎SEO体验度的功能,一般的SEO插件都有,但是如果我们不用的话可以直接自己添加代码。

add_action( 'wp_head', 'wp_head_example' );
 
function wp_head_example() {
    global $post;
     
    // default image
    $site_logo = get_stylesheet_directory_uri() . '/images/logo.png';
     
    // homepage
    if ( is_home() ) {
        echo '<meta property="og:type" content="website" />';
        echo '<meta property="og:url" content="' . get_bloginfo( 'url' ) . '" />';
        echo '<meta property="og:title" content="' . esc_attr( get_bloginfo( 'name' ) ) . '" />';
        echo '<meta property="og:image" content="' . $site_logo . '" />';
        echo '<meta property="og:description" content="' . esc_attr( get_bloginfo( 'description' ) ) . '" />';
    }
     
    // single post or page
    elseif ( is_singular() ) {
        echo '<meta property="og:type" content="article" />';
        echo '<meta property="og:url" content="' . get_permalink() . '" />';
        echo '<meta property="og:title" content="' . esc_attr( get_the_title() ) . '" />';
        if ( has_post_thumbnail( $post->ID ) ) {
            $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'large' );
            echo '<meta property="og:image" content="' . esc_attr( $image[0] ) . '" />';
        } else
            echo '<meta property="og:image" content="' . $site_logo . '" />';
        echo '<meta property="og:description" content="' . esc_attr( get_the_excerpt() ) . '" />';
    }
}

这里参考:https://code.tutsplus.com/tutorials/fifty-actions-of-wordpress-50-examples-31-to-40–cms-21581

我们可以实现基本的 Open Graph协议 添加到头部,首页和内容页是有区别的。

5/5 - (1 vote)
© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享