4.7/5 - (4 bình chọn)

Dạo này thấy một vài web có cái thời gian đọc bài viết kiểu hình bên dưới.

bnixvn doc screenshot 2024 02 11 105051

Vì vậy hôm nay mình share code này, các bạn copy dán vào functions.php rồi dùng shortcode chèn vào chỗ muốn hiển thị

/**
 *
 * Post estimated reading time shortcode
 *
 */
function bnix_reading_time_shortcode() {
	$content = get_post_field( 'post_content', $post->ID );
	$word_count = str_word_count( strip_tags( $content ) );
	$readingtime = ceil($word_count / 200);
	$totalreadingtime = '<div class="reading-time">Thời gian đọc: '.$readingtime . ' phút</div>';
	return $totalreadingtime;
}
add_shortcode('readingshortcode', 'bnix_reading_time_shortcode');

Và nếu muốn chèn tự động vào bài viết, chúng ta sử dụng code dưới đây:

/**
 *
 * Post estimated reading time shortcode
 *
 */
function bnix_reading_time_shortcode($content) {
	$word_count = str_word_count( strip_tags( $content ) );
	$readingtime = ceil($word_count / 200);
	$totalreadingtime = '<div class="reading-time">Thời gian đọc: '.$readingtime . ' phút</div>';
	return $totalreadingtime.$content;
}
add_filter('the_content', 'bnix_reading_time_shortcode',20);

Chúc các bạn sử dụng thành công!

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *