问题描述
在用于社交共享的 wordpress 中,我使用 yoast SEO 插件。现在根据客户要求,我需要为 og:image 设置如下条件。
- 如果在帖子/页面的 yoast 元框中添加了图像,则显示该图像
- 如果 yoast SEO 中没有图片,请检查帖子/页面中的特色图片
- 如果 yoast SEO 和特色图像中没有图像,则显示设置中的一些图像。 我如何知道图像是否已上传到特定页面的 yoast Meta Box 中并满足上述要求? 我尝试了以下操作,但它只替换了 yoast Meta Box 中的图像。
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_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] ) . '"/>';
}
}