Home  >  Article  >  php教程  >  WordPress获取文章(相册)中图片的数量

WordPress获取文章(相册)中图片的数量

WBOY
WBOYOriginal
2016-06-06 20:11:201436browse

1. 需求 小站的相册分类中文章主要有两种,一种使用的是WordPress的原生相册功能,另外一种则是普通的文章,文章内插入了图片;本文的需求就是统计文中的图片的总张数。 演示效果见:http://loosky.net/archives/category/album。 2. 解决方案 获取文章图片

1. 需求

小站的相册分类中文章主要有两种,一种使用的是WordPress的原生相册功能,另外一种则是普通的文章,文章内插入了图片;本文的需求就是统计文中的图片的总张数。

演示效果见:http://loosky.net/archives/category/album。

演示图片

2. 解决方案

获取文章图片数量函数

将函数post_img_number放在functions.php中。

function post_img_number(){
    global $post, $posts;
    ob_start();
    ob_end_clean();
    //使用do_shortcode($post->post_content) 是为了处理在相册的情况下统计图片张数
    $output = preg_match_all('//i',do_shortcode($post->post_content), $matches);
    $cnt = count( $matches[1] );
    return $cnt;
}

注:本函数最大的改进是通过使用do_shortcode($post->post_content)来调用WordPress文章的内容而不是使用$post->post_content,可以解决使用原生相册功能功能时图片不能统计的问题。

调用函数

调用方法为:

<?php echo post_img_number().'张'; ?>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn