获取WordPress文章中图片的数量

2024年3 月13日 / 网站源码 / 没有评论 / 4,180次

要获取WordPress文章内的图片数量,你可以使用以下代码片段:

一、在你的主题文件(例如functions.php)中:

  1. // WordPress获取文章内图片数量
  2. if( !function_exists('get_post_images_number') ){
  3.     function get_post_images_number(){
  4.         global $post;
  5.         $content = $post->post_content;
  6.         preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $content$result, PREG_PATTERN_ORDER);
  7.         return count($result[1]);
  8.     }
  9. }

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

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

提交评论