【问题标题】:how to know yoast seo image is uploaded or not and add conditions for og:image in wordpress如何知道 yoast seo 图片是否上传并在 wordpress 中为 og:image 添加条件
【发布时间】:2020-12-23 05:58:59
【问题描述】:

在用于社交分享的 WordPress 中,我使用的是 yoast seo 插件。现在根据客户要求,我需要为 og:image 设置如下条件。

  1. 如果在 yoast 元框中为帖子/页面添加了图片,则显示该图片
  2. 如果 yoast seo 中没有图片,请检查帖子/页面中的特色图片
  3. 如果 yoast seo 中没有图像,并且特色图像显示设置中的一些图像。 我如何知道图像是否上传到特定页面的 yoast 元框中并满足上述要求? 我尝试了以下方法,但它只替换了 yoast 元框中的图像。
add_filter( 'wpseo_opengraph_image', 'ag_yoast_seo_fb_share_images', 10, 1 );

function ag_yoast_seo_fb_share_images( $img ) {

    return ( $img && ! empty( $img ) ) ?  $img : get_field( 'social_share_image', 'options' );
};

【问题讨论】:

  • 我没有测试真正的情景。但希望它对你有用。因此您可以通过以下代码进行检查: add_filter( 'wpseo_opengraph_image', 'ag_yoast_seo_fb_share_images', 10, 1 );功能 ag_yoast_seo_fb_share_images( $img ) { 全球 $post; if( $img && !empty( $img ) ) { return $img; } else if ( is_page() || is_single() ) { $image = get_the_post_thumbnail_url($post->ID, 'full'); if (empty($image)) { return get_field( 'social_share_image', 'options' ); } 其他 { 返回 $image; } } else { return get_field( 'social_share_image', 'options' ); } };

标签: wordpress share yoast


【解决方案1】:

以下解决方案对我有用。

add_action( 'wp_head', 'insert_fb_in_head', 5 );
    function insert_fb_in_head() {
        global $post;
        if( ! has_post_thumbnail( $post->ID ) ) { //the post does not have featured image, use a default image
            $default_image = get_field( 'social_share_image', 'options' ); //replace this with a default image on your server or an image in your media library
            echo '<meta property="og:image" content="' . $default_image . '"/>';
        } else{
            $thumbnail_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' );
            echo '<meta property="og:image" content="' . esc_attr( $thumbnail_src[0] ) . '"/>';
        }
    }

【讨论】:

    猜你喜欢
    • 2012-03-13
    • 1970-01-01
    • 2014-10-05
    • 2020-06-13
    • 2011-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多