【问题标题】:Find first image from post content with wordpress使用 wordpress 从帖子内容中查找第一张图片
【发布时间】:2017-12-20 11:01:19
【问题描述】:

我正在尝试从我的每个帖子内容中获取第一张图片。下面的代码不起作用。但是,如果我有多个图像,则给我一个图像,但最后一个图像。

我真的只想要第一张图片。

function catch_that_image($post_content) {
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post_content, $matches);
$first_img = $matches [1] [0];
return $first_img;

}

【问题讨论】:

    标签: php wordpress image post preg-match-all


    【解决方案1】:

    首先,将此函数粘贴到您的functions.php 文件中。

    function catch_that_image() {
      global $post, $posts;
      $first_img = '';
      ob_start();
      ob_end_clean();
      $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
      $first_img = $matches [1] [0];
    
      if(empty($first_img)){ //Defines a default image
        $first_img = "/images/default.jpg";
      }
      return $first_img;
    }
    

    完成后,您只需在循环中调用该函数即可显示帖子中的第一张图片:

    <?php echo catch_that_image() ?>
    

    这里是link

    【讨论】:

    • 我做了同样的事情,但我仍然从内容中获得了第三张图片。
    • 请问您是否尝试将帖子内容的第一张图片作为特色图片?或者你想获取它并想在某个地方显示,如果是的话,你试图显示它?
    • 另外,您是否尝试更改 $first_img = $matches [1] [0]; 数组中的值?然后尝试生态这个。
    • 我有自定义帖子列表页面,我想在循环中显示帖子内容中的第一张图片和帖子标题。我添加了自定义图片而不是媒体网址。
    猜你喜欢
    • 2011-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多