WordPress获取文章的第一个图片地址的方法

我们知道 WordPress 有个日志缩略图的功能(特色图像),需要你自己上传一张图片或者选择已有的图片,然后设置为特色图像,这样就可以在博客首页或者其他地方即可使用。

图片[1]_WordPress获取文章的第一个图片地址的方法_知途无界

但是这样比较麻烦,需要每次都要上传或者选择下,是否可以有更简洁的方法,其实我们还可以直接获取日志中的第一张图片。

//获取文章第一张缩略图
function catch_that_image() {
global $post;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img*.+src=[\'"]([^\'"]+)[\'"].*>/iU', wp_unslash($post->post_content), $matches);
if(empty($output)){
//如果没有图片,则调用默认图片
$first_img = "https://zhituwujie.com/wp-content/themes/zibll/img/default.jpg";
}else {
$first_img = $matches [1][0];
}
return $first_img;
}
//获取文章第一张缩略图 
function catch_that_image() {
  global $post;
  $first_img = '';
  ob_start();
  ob_end_clean();
  $output = preg_match_all('/<img*.+src=[\'"]([^\'"]+)[\'"].*>/iU', wp_unslash($post->post_content), $matches);
  if(empty($output)){ 
                 //如果没有图片,则调用默认图片
    $first_img = "https://zhituwujie.com/wp-content/themes/zibll/img/default.jpg";
  }else {
    $first_img = $matches [1][0];
  }
  return $first_img;
}
//获取文章第一张缩略图 function catch_that_image() { global $post; $first_img = ''; ob_start(); ob_end_clean(); $output = preg_match_all('/<img*.+src=[\'"]([^\'"]+)[\'"].*>/iU', wp_unslash($post->post_content), $matches); if(empty($output)){ //如果没有图片,则调用默认图片 $first_img = "https://zhituwujie.com/wp-content/themes/zibll/img/default.jpg"; }else { $first_img = $matches [1][0]; } return $first_img; }

将上面的代码复制到当前主题的 functions.php,然后使用下面的方式引用:

echo catch_that_image();
echo catch_that_image();
echo catch_that_image();
© 版权声明
THE END
喜欢就点个赞,支持一下吧!
点赞32 分享
Not all of us can offord to be romantic.
并不是我们所有的人都会拥有浪漫
评论 抢沙发
头像
欢迎您留下评论!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容