Posted in: WordPress

无插件实现WordPress的Galaxis主题的post页面中显示浏览次数

无插件实现Wordpress的Galaxis主题的post页面中显示浏览次数

一、效果展示

  1. 主页效果展示,我的主页设置为显示最新的post

file

  1. 单独页效果展示

file

  1. 搜索页面效果展示

file

二、实现方法

1. 将下面的文章点击量统计代码添加到你主题的functions.php的最后一个 ?> 的前面

注:如果结尾没有?>则直接添加到最后

针对galaxis主题具体方法就是从WordPress的目录中找到wp-content\themes\galaxis\functions.php,直接在结尾添加

/* 访问计数 */
function record_visitors()
{
    if (is_singular()) 
    {
      global $post;
      $post_ID = $post->ID;
      if($post_ID) 
      {
          $post_views = (int)get_post_meta($post_ID, 'views', true);
          if(!update_post_meta($post_ID, 'views', ($post_views+1))) 
          {
            add_post_meta($post_ID, 'views', 1, true);
          }
      }
    }
}
add_action('wp_head', 'record_visitors');  
 
/// 函数名称:post_views 
/// 函数作用:取得文章的阅读次数
function post_views($before = '(点击 ', $after = ' 次)', $echo = 1)
{
  global $post;
  $post_ID = $post->ID;
  $views = (int)get_post_meta($post_ID, 'views', true);
  if ($echo) echo $before, number_format($views), $after;
  else return $views;
}

2. 然后在需要显示点击数的地方添加下面的调用代码即可

阅读:<?php post_views(' ', ' 次'); ?>

针对galaxis主题,需要将以下代码添加在这三个位置
post_views(' ', ' 次');

file

添加的位置为:

//某个post单独页面

wp-content\themes\galaxis\template-parts\content-single.php

//搜索结果展示页面

wp-content\themes\galaxis\template-parts\content-search.php

//博客首页

wp-content\themes\galaxis\template-parts\content.php

Comments (2) on "无插件实现WordPress的Galaxis主题的post页面中显示浏览次数"

Comments are closed.

Back to Top