wordpress

WordPress技巧:获取统计文章内图片数量

admin · 3月31日 · 2021年 · 614次已读

据我所知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]);    
    }  
}  

然后在需要统计文章内图片数量的地方添加下面代码即可。

注意: 使用时需要放在循环内。

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

统计文章字数的数量

// 字数统计
function zm_count_words ($text) {
	global $post;
	if ( '' == $text ) {
		$text = $post->post_content;
		if (mb_strlen($output, 'UTF-8') < mb_strlen($text, 'UTF-8')) $output .= '<span class="word-count">共' . mb_strlen(preg_replace('/\s/','',html_entity_decode(strip_tags($post->post_content))),'UTF-8') .'字</span>';
		return $output;
	}
}

调用方式

<?php echo count_words ($text); ?>

文章阅读时间

// 阅读时间
function zm_get_reading_time($content) {
	$zm_format = '<span class="reading-time">阅读时间%min%分%sec%秒</span>';
	$zm_chars_per_minute = 300; // 估算1分种阅读字数
 
	$zm_format = str_replace('%num%', $zm_chars_per_minute, $zm_format);
	$words = mb_strlen(preg_replace('/\s/','',html_entity_decode(strip_tags($content))),'UTF-8');
 
	$minutes = floor($words / $zm_chars_per_minute);
	$seconds = floor($words % $zm_chars_per_minute / ($zm_chars_per_minute / 60));
	return str_replace('%sec%', $seconds, str_replace('%min%', $minutes, $zm_format));
}
 
function zm_reading_time() {
	echo zm_get_reading_time(get_the_content());
}

代码添加到当前主题函数模板 functions.php 中,然后用下面的代码调用,不过字数统计和阅读时间不是很精确,特别是阅读时间,更是扯淡,默认是按CCTV广播员语速定的。

<?php zm_reading_time(); ?>