我们知道 WordPress 有个日志缩略图的功能(特色图像),需要你自己上传一张图片或者选择已有的图片,然后设置为特色图像,这样就可以在博客首页或者其他地方即可使用。
![图片[1]_WordPress获取文章的第一个图片地址的方法_知途无界](https://zhituwujie.com/wp-content/uploads/2024/04/4a47a0db6e20240414172403.png)
但是这样比较麻烦,需要每次都要上传或者选择下,是否可以有更简洁的方法,其实我们还可以直接获取日志中的第一张图片。
//获取文章第一张缩略图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
暂无评论内容