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

很多博客会将阅读量、点评数或者好评数高的文章进行输出展示给大家.

于是纯代码版本的阅读数和好评数功能就来了,主要使用了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;
  }