WordPress如何获取统计文章内图片数量

追格官方小助手/ 2022年03月10日/ WordPress/ 浏览 1488

WordPress怎么获取统计文章内图片数量,WordPress本身是没有统计文章内图片数量的函数,我们可以用下面方式试试。


在当前WordPress主题的函数文件functions.php加入以下代码:


// WordPress获取文章内图片数量
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]);    
    }  
}  


2、在统计文章内图片数量的地方添加以下代码调用:


<?php echo get_post_images_number().'张图片' ?>  


发表评论

暂无评论,抢个沙发...

客服 工单