在WordPress页面上动态插入og:image
我正在使用以下函数,并在我确定具有特色图像集的页面上使用FB的调试器:在WordPress页面上动态插入og:image,wordpress,facebook-opengraph,Wordpress,Facebook Opengraph,我正在使用以下函数,并在我确定具有特色图像集的页面上使用FB的调试器: function fb_opengraph() { global $post; if(is_page()) { if(has_post_thumbnail($post->ID)) { $img_src = wp_get_attachment_image_src(get_post_thumbnail_id( $post->ID ), 'medium');
function fb_opengraph() {
global $post;
if(is_page()) {
if(has_post_thumbnail($post->ID)) {
$img_src = wp_get_attachment_image_src(get_post_thumbnail_id( $post->ID ), 'medium');
} else {
$img_src = get_stylesheet_directory_uri() . '/img/opengraph_image.jpg';
}
if($excerpt = $post->post_excerpt) {
$excerpt = strip_tags($post->post_excerpt);
$excerpt = str_replace("", "'", $excerpt);
} else {
$excerpt = get_bloginfo('description');
}
?>
<meta property="og:title" content="<?php echo the_title(); ?>"/>
<meta property="og:description" content="<?php the_content(); ?>"/>
<meta property="og:type" content="article"/>
<meta property="og:url" content="<?php echo the_permalink(); ?>"/>
<meta property="og:site_name" content="<?php echo get_bloginfo(); ?>"/>
<meta property="og:image" content="<?php echo $img_src; ?>"/>
<?php
} else {
return;
}
}
add_action('wp_head', 'fb_opengraph', 5);
函数fb_opengraph(){
全球$员额;
如果(是页面()){
如果(有帖子缩略图($post->ID)){
$img_src=wp_get_attachment_image_src(get_post_缩略图_id($post->id),'medium');
}否则{
$img_src=get_stylesheet_directory_uri()。/img/opengraph_image.jpg';
}
如果($extract=$post->post_摘录){
$excerpt=带标签($post->post\U excerpt);
$excerpt=str_替换(“,”,$excerpt);
}否则{
$extracpt=get_bloginfo('description');
}
?>
这将为您提供一个数组
wp_get_attachment_image_src(get_post_thumbnail_id( $post->ID ), 'medium');
要获取url,需要获取适当的数组元素
$img_src = wp_get_attachment_image_src(get_post_thumbnail_id( $post->ID ), 'medium')['url'];
试试看
wp_get_attachment_image_src(get_post_thumbnail_id( $post->ID ), 'medium');
它将返回一个数组。此数组的第一个元素将包含图像URL
因此,您需要这样提及此数组的第一个索引:$img\u src[0]
全线将是:
<meta property="og:image" content="<?php echo $img_src[0]; ?>"/>
感谢您的快速响应。我已经添加了该代码,目前$img_src没有任何价值。根据FB的调试器,提供的og:image URL不是有效的URL。我已经双重检查了那里确实有一个特色图像。尝试通过浏览器查看页面源代码。src中有什么?很简单“”对于og:image:然后尝试$img\u src=wp\u get\u attachment\u image\u src(get\u post\u thumbnail\u id($post->id),'medium')[0];如果它不起作用,那么我会打印(wp\u get\u attachment\u image\u src(get\u post\u thumbnail\u id($post->id),'medium'))然后看看输出是什么。也许它根本无法获取图像数组,但我真的无法发现任何错误。从技术上讲,如果我没有遗漏某些内容,它应该可以工作。成功了!非常感谢——非常感谢。干杯!