【问题标题】:Dynamically inserting og:image on a WordPress page在 WordPress 页面上动态插入 og:image
【发布时间】:2016-08-21 23:25:57
【问题描述】:

我正在使用以下功能,并且在我确定有特色图片集的页面上使用 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');
        } 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);

当前发生的情况是 $img_src 返回值为“Array”,而不是该页面的特色图像的 URL。我不确定这个“数组”值是从哪里来的,但更重要的是我试图在没有运气的情况下提取特色图片 URL。

有什么想法吗?谢谢!

【问题讨论】:

    标签: wordpress facebook-opengraph


    【解决方案1】:
    wp_get_attachment_image_src(get_post_thumbnail_id( $post->ID ), 'medium');
    

    它将返回一个数组。该数组的第一个元素将包含图像 URL。

    所以你需要这样提到这个数组的第一个索引:$img_src[0]

    整行将是:

    <meta property="og:image" content="<?php echo $img_src[0]; ?>"/>
    

    【讨论】:

      【解决方案2】:

      https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/

      这应该给你一个数组

      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'];
      

      试试看

      【讨论】:

      • 感谢您的快速响应。我已经添加了该代码,它目前返回时对 $img_src 毫无价值。 “提供的 og:image URL,不是有效的 URL。”,根据 FB 的调试器。我仔细检查了那里确实有一张特色图片。
      • 尝试通过浏览器查看页面源代码。 src 里面有什么?
      • og:image 只是“”: jmak.com/11-cadogan-gardens/">
      • 然后尝试 $img_src = wp_get_attachment_image_src(get_post_thumbnail_id( $post->ID ), 'medium')[0];如果它不起作用,那么我会 print_r(wp_get_attachment_image_src(get_post_thumbnail_id( $post->ID ), 'medium')) 并查看输出。也许它根本无法获取图像数组,但我无法真正发现任何错误。从技术上讲,如果我没有遗漏什么,它应该可以工作。
      • 成功了!非常感谢——非常感谢。干杯!
      猜你喜欢
      • 1970-01-01
      • 2013-01-10
      • 2012-03-24
      • 2012-12-14
      • 2013-05-14
      • 2011-03-14
      • 2015-10-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多