WordPress主题开发的时候,有这个需求:文章列表统计显示文章内图片数量,如本截图显示.
相关文章: WordPress主题开发:文章列表添加统计显示文章字数
打开当前WordPress主题开发的functions.php文件,在<?php下面的?>前面添加如下代码:
/** * 文章标题:WordPress文章列表统计显示文章内图片数量方法一 * 文章链接:https://www.wpyi.com/tupian-shuliang.html */ function wpyi_post_images_number(){ global $post; $content = $post->post_content; preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $content, $strResult, PREG_PATTERN_ORDER); return count($strResult[1]); }
在文章列表的模板里要显示文章内图片数量的地方,archive.php内添加下面的代码:
// 直接输出图片数量 <?php echo '共有' . wpyi_post_images_number() . '张图片'; ?>
需要自己完善样式
复制以下代码到当前使用主题的functions.php文件中,然后在文章列表主循环或文章页中调用该函数即可。
//获取文章中的图片个数 //文章链接:https://www.wpyi.com/tupian-shuliang.html if( !function_exists('get_post_images_number') ){ function get_post_images_number(){ global $post; $content = $post->post_content; preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $content, $result, PREG_PATTERN_ORDER); return count($result[1]); } }
在文章列表的模板里要显示文章内图片数量的地方,archive.php内添加下面的代码:
<?php echo get_post_images_number().'张图片' ?>