使用wordpress从帖子内容中查找第一张图片

问题描述 投票:0回答:1

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

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

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个回答
0
投票

首先,将此函数粘贴到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

© www.soinside.com 2019 - 2024. All rights reserved.