在文章中显示阅读次数
一 在functions.php尾添加以下代码
function getPostViews($postID){ $count_key = 'views'; $count = get_post_meta($postID, $count_key, true); if($count==''){ delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); return "阅读次数 0"; } return '阅读次数 '.$count; } function setPostViews($postID) { $count_key = 'views'; $count = get_post_meta($postID, $count_key, true); if($count==''){ $count = 0; delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); }else{ $count++; update_post_meta($postID, $count_key, $count); } }
二 在single.php中添加以下代码
<?php setPostViews(get_the_ID()); ?>
三 在想显示的地方添加以下代码,如:
- template-parts/content.php
- template-parts/content-single.php
<?php echo getPostViews(get_the_ID()); ?>