摘要:
在测试之后,代码二方法相对简单,它与我们使用的wp-postviews插件的自定义列相同。换句话说,在我们禁用wp-postviews插件后,使用此代码不会影响原始文章读数。但是,建议不要直接在后台删除wp-postviews插件。据说这个删除将是数据库中的原始。读取的文章数量已完全清除。建议直接通过FTP删除wp-postviews插件文件。
一般添加Wordpress文章的阅读统计,你将使用wp-postviews或wp-postviews-plus插件,这里分享两段没有插件来实现Wordpress文章的阅读时间供你参考。
代码一:
首先,将以下代码添加到主题函数模板文件中:
- function getPostViews($postID){
- $count_key = ‘post_views_count’;
- $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 View”;
- }
- return $count.’ Views’;
- }
- function setPostViews($postID) {
- $count_key = ‘post_views_count’;
- $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);
- }
- }
其次,将以下代码添加到主题单模板主循环中:
- <?php setPostViews(get_the_ID()); ?>
这类似于以下句子
- <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
第三,最后,将显示读取代码调用到single模板的适当位置:
- <?php echo getPostViews(get_the_ID()); ?>
如果要显示其他位置的读数数量,还可以将以下代码添加到功能模板中:
- remove_action(’wp_head’,’adjacent_posts_rel_link_wp_head’,10,0);
原始:Track post views without a plugin using post meta
代码二:
首先,将以下代码添加到主题函数模板文件中:
- //postviews
- function get_post_views ($post_id) {
- $count_key = ‘views’;
- $count = get_post_meta($post_id, $count_key, true);
- if ($count == ”) {
- delete_post_meta($post_id, $count_key);
- add_post_meta($post_id, $count_key, ‘0’);
- $count = ‘0’;
- }
- echo number_format_i18n($count);
- }
- function set_post_views () {
- global $post;
- $post_id = $post -> ID;
- $count_key = ‘views’;
- $count = get_post_meta($post_id, $count_key, true);
- if (is_single() || is_page()) {
- if ($count == ”) {
- delete_post_meta($post_id, $count_key);
- add_post_meta($post_id, $count_key, ‘0’);
- } else {
- update_post_meta($post_id, $count_key, $count + 1);
- }
- }
- }
- add_action(‘get_header’, ‘set_post_views’);
第二,调用将读取频率代码显示到single模板的适当位置:
- <?php get_post_views($post -> ID); ?> views
呼叫显示读取代码也可以添加到其他模板文件的适当位置。
代码i来自:M2主题,原文来自于https://boke112.com
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article. https://accounts.binance.com/sk/register?ref=FIHEGIZ8