海天无影Blog

wordpress新增阅读数和好评数功能

/ 2852阅 / 0评 / 0

很多博客会将阅读量、点评数或者好评数高的文章进行输出展示给大家。海天使用的Adams主题,已经包含了点赞好评的功能,但是通过上次分析博客的访问流量之后,发现阅读量高的文章其实被点赞数并不多,可能只因为主题的好评功能并不明确,那么如何分享博客中好的文章,阅读数的统计功能就很有必要了。

于是纯代码版本的阅读数和好评数功能就来了,主要使用了wordpress的 get_post_meta()、delete_post_meta()、add_post_meta()、add_action() 这几个函数。

其中 add_action() 函数用于好评提交的ajax功能,其他三个函数就是操作meta表的函数。

设置或更新阅读数

/**
  * set_post_views()函数
  * 功能:设置或更新阅读数量
  * 在内容页面调用此函数
  * 需要传入文章的id,也就是 $post->ID
  * 返回文章阅读数
  */
  function set_post_views( $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 );
    }
    return $count;
  }

获取阅读数

/**
  * get_post_views()函数
  * 功能:获取阅读数量
  * 在需要显示阅读数的位置,调用此函数
  * 需要传入文章的id,也就是 $post->ID
  * 返回文章阅读数
  */
  function get_post_views( $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;
  }

设置或更新好评数

/**
  * set_post_good()函数
  * 功能:设置或更新好评数量
  * 在内容页ajax调用此函数
  * 返回文章好评数
  */
  function set_post_good() {
    $postID = $_POST['id'];
    $count_key = 'good';
    $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 );
    }
    wp_die();
  }
  add_action( 'wp_ajax_set_post_good', 'set_post_good' );
  add_action( 'wp_ajax_nopriv_set_post_good', 'set_post_good' );
  //wordpress 中 ajax 提交需要用到 add_action() 函数

获取好评数

/**
  * get_post_good()函数
  * 功能:获取好评数
  * 在需要显示好评数的位置,调用此函数
  * 需要传入文章的id,也就是 $post->ID
  * 返回文章好评数量
  */
  function get_post_good( $postID ) {
    $count_key = 'good';
    $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;
  }

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注