WordPress获取文章中的图片个数

2019年12月16日13:22:28 发表评论 热度376 ℃

丰富wordpress主题的info tags 除了分类、标签、作者、发布时间等等外,其实,我们也可以放出文章内的图片数量,那么今天说的就是WordPress获取文章中的图片个数的教程!
复制以下代码到当前使用主题的functions.php文件中,然后在文章列表主循环或文章页中调用该函数即可。

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

函数使用方法:

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

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: