Skip to main content
We are Brand SEO Beijing serving international business, your marketing partner, Contact us by mi@mgsh.com.cn

The website realizes the function of user points

The idea of ​​website points is sorted out:

1. Two data sheets need to be prepared.
(1) Points dynamic table, used to record the increase or decrease of points for all users.
(2) The total user points table is used to record the total points of users. Of course, the total number of user points can be recorded in the usermeta data table, so this table is not necessary.
2. The background requires 3 pages.
(1) Points dynamics, obtain data from the "Points Dynamics Table" to display the user points dynamics.
(2) User points, obtain data from the "User Points Table", which is convenient to check the total points of users.
(3) Points increase and decrease page, used to increase or decrease points for users.
(Warning: The code is for reference.)

XNUMX. Create a new data table

1. Integral dynamic tableThe fields in points_activity are id, user id, points (number of transactions), description, balance, and time.
2. User Points TableThere are only two fields in points: user id and number of points.

// Executed when the theme is enabled for the first time. function ashuwp_load_theme() { global $pagenow; if ( is_admin() && 'themes.php' == $pagenow && isset( $_GET['activated'] ) ){ ashuwp_points_install(); } } add_action( 'load-themes. php', 'ashuwp_load_theme' ); //Create new data table points_activity and points function ashuwp_points_install(){ global $wpdb; $table_name = $wpdb->prefix . 'points_activity'; //Integration dynamic table $table_name2 = $wpdb-> prefix . 'points'; //Points summary table $charset_collate = $wpdb->get_charset_collate(); if( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name ) : $sql = " CREATE TABLE `".$table_name."` ( `id` BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY , `user_id` BIGINT(40), `points` INT NOT NULL, `description` longtext, `balance` INT NOT NULL, `date ` DATETIME NOT NULL ) $charset_collate;"; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); endif; if( $wpdb->get_var("SHOW TABLES LIKE '$table_name2 '") != $table_name2 ) : $sql2 = " CREATE TABLE `".$table_name2."` ( `user_id` BIGINT(40) NOT NULL AUTO_INCREMENT PRIMARY KEY , `points` INT NOT NULL ) $charset_collate;"; dbDelta($sql2); endif; }

Second, the database operation function

First, the user points tablepointsThe operations required by the user points only need to update and obtain two operations.

//Get a user's points according to the user id function ashuwp_get_user_points($user_id){ global $wpdb; $user = get_user_by('ID', $user_id); if(!$user){ return 0; } $points_table = $wpdb->prefix . 'points'; $sql = "select points from ".$points_table." where user_id={$user_id}"; $result = $wpdb->get_var($sql); if(!$result ){ return 0; }else{ return $result; } } //Update (add) user points. function ashuwp_update_user_points($user_id, $new_points){ global $wpdb; $user = get_user_by('ID', $user_id) ; if(!$user){ $msg = array( 'state' => 'error', 'msg' => 'User Error', ); return $msg; } if( !is_numeric($new_points)|| $ new_points<0){ $msg = array( 'state' => 'error', 'msg' => 'Points not number or points error', ); return $msg; } $points_table = $wpdb->prefix . ' points'; $points_exist = $wpdb->get_var( "select count(*) from {$points_table} where user_id='{$user_id}'" ); if($points_exist){ $sql = "update {$points_table} set points='{$new_points}' where user_id='{$user_id}'"; }else{ $sql = "insert into {$points_table} ( user_id, points )values( '{$user_id}', '{$new_points}' )";; } $result = $wpdb->query($sql); if($result){ $msg = array( 'state' => ' succeed', 'msg' => 'Points Updated.', ); return $msg; }else{ $msg = array( 'state' => 'error', 'msg' => 'Points update failed.', ) ; return $msg; } } //Get data from the user points table, the background point summary page needs to get data. function ashuwp_get_points( $args=array() ){ global $wpdb; $defaults = array( 'per_page' => '50', 'paged' => '1', ); $args = wp_parse_args( $args, $defaults ); $page = (int)$args['paged']; $per_page = (int)$args['per_page']; if(!$page){ $page = 1; } if(!$per_page){ $per_page = 50; } $begin = $per_page*($page-1); $end = $per_page*$page; $points_table = $wpdb->prefix . 'points'; $sql = "select * from $points_table order by user_id asc limit $begin,$end"; $results = $wpdb->get_results($sql,'ARRAY_A'); return $results; } //Count the number of data, the background points summary page needs to obtain data. function ashuwp_count_points(){ global $wpdb; $points_table = $wpdb->prefix . 'points'; $sql = "select count(*) from $points_table"; $results = $wpdb->get_var($sql); return $results; }

Then, the operation on the dynamic table of integrals only needs to be added, and does not need to be deleted.

/*Add a point dynamic*/ function ashuwp_add_points_activity( $args=array() ){ global $wpdb; $defaults = array( 'user_id' => '', 'action' => '', 'points' => '', 'description' => '', 'date' => '' ); $args = wp_parse_args( $args, $defaults ); //Determine whether the user id is legal $user = get_user_by('ID', $args ['user_id']); if(!$user){ $msg = array( 'state' => 'error', 'msg' => 'User Error', ); return $msg; } // only increment the sum Reduce two operations. if( !in_array( $args['action'], array( 'add', 'reduce' ) )){ $msg = array( 'state' => 'error', 'msg' => 'Operate Error', ); return $msg; } //Check whether the integral change number is legal if( !is_int($args['points']) ){ $msg = array( 'state' => 'error', 'msg' => ' Points Error', ); return $msg; } //Processing description $args['description'] = sanitize_text_field($args['description']); //Processing transaction number, and calculating balance $old_points = (int)ashuwp_get_user_points ($args['user_id']); if($args['action']=='add'){ $balance = $old_points+$args['points']; $change = $args['points']; if($balance!=$old_points){ //Update the new balance to the user points table. $update = ashuwp_update_user_points($args['user_id'],$balance); } } if($args['action']=='reduce'){ $balance = $old_points-$args['points']; $ change = -$args['points']; //If it is reduced, it will be stored as a negative number in the database. if($balance!=$old_points){ $update = ashuwp_update_user_points($args['user_id'],$balance); } } if( ($balance!=$old_points) && $update['state'] != ' succeed' ){ $msg = array( 'state' => 'error', 'msg' => $update['msg'], ); return $msg; } $table_name = $wpdb->prefix .  'points_activity'; //Insert data $args['date'] = date( "Ymd H:i:s", time()); $sql = "insert into $table_name ( user_id, points, description, balance, date ) values( '{$args['user_id']}', '{$change}', '{$args['description']}', '{$balance}', '{$args['date'] }' )"; $result = $wpdb->query($sql); if($result){ $msg = array( 'state' => 'succeed', 'msg' => 'succeed!', ); return $msg; }else{ //If dynamic insertion fails, roll back the user points table. ashuwp_update_user_points($args['user_id'],$old_points); $msg = array( 'state' => 'error', 'msg' => 'Insert Error', ); return $msg; } } /* from points Get data from the dynamic table, which is required in the background page. * Need to support conditional query to facilitate background management. */ function ashuwp_get_points_activity( $args=array() ){ global $wpdb; $defaults = array( 'user_id' => '', 'per_page' => '50', 'paged' => '1', 'action ' => '' ); $args = wp_parse_args( $args, $defaults ); //Process page numbers $page = (int)$args['paged']; $per_page = (int)$args['per_page'] ; if(!$page){ $page = 1; } if(!$per_page){ $per_page = 50; } $begin = $per_page*($page-1); $end = $per_page*$page; $ table_name = $wpdb->prefix .  'points_activity'; $sql = "select * from $table_name where 1=1 "; //Query user id if($args['user_id']!=''){ $user_id = (int)$args['user_id ']; $sql .= "and user_id='{$user_id}' "; } //Query operation type if( in_array( $args['action'], array( 'add', 'reduce', 'remain' ) ) ){ if($args['action']=='add'){ $sql .= "and points>0 "; } if($args['action']=='reduce'){ $sql .= "and points<0 "; } if($args['action']=='remain'){ $sql .= "and points=0 "; } } $sql .= "order by id desc limit $ begin,$end"; $results = $wpdb->get_results($sql,'ARRAY_A'); return $results; } /*Number of dynamic records of statistical points* Add statistical conditions to facilitate background management*/ function ashuwp_count_points_activity( $args =array() ){ global $wpdb; $defaults = array( 'user_id' => '', 'action' => '' ); $args = wp_parse_args( $args, $defaults ); $table_name = $wpdb- >prefix . 

XNUMX. Create a background page

1. Points dynamic page.
The background page is designed to the application of the class-wp-list-table class, so there is no need to add comments one by one.

if(!class_exists('WP_List_Table')) { require_once( ABSPATH .  'wp-admin/includes/class-wp-list-table.php' );
}
class Ashuwp_Points_Activity_Table extends WP_List_Table {
  function __construct(){
    parent::__construct( array(
      'singular'  => 'Points Activity',
      'plural'    => 'Points Activity',
      'ajax'      => false
    ) );
  }
  function column_default( $item, $column_name ) {
    switch ( $column_name ){
      case 'id':
      case 'user':
      case 'points':
      case 'balance':
      case 'description':
      case 'date':
        return $item[ $column_name ];
      default:
        return print_r($item,true);
    }
  }
  function get_columns() {
    $columns = array(
      'id'       => 'ID',
      'user'    => 'User',
      'points'      => 'Points',
      'balance'     => 'Balance',
      'description' => 'Description',
      'date'    => 'Date',
    );
    return $columns;
  }
  function format_activity( $datas ) {
    $return_datas = array();
    foreach( $datas as $data ){
      $user = get_user_by('id', $data['user_id']);
      $item_array = array();
      $item_array['id'] = $data['id'];
      $item_array['user'] = $user->user_login;
      if($data['points']<0){
        $item_array['points'] = '<span class="reduce">'.$data['points'].'</span>';
      }elseif($data['points']>0){
        $item_array['points'] = '<span class="add">+'.$data['points'].'</span>';
      }else{
        $item_array['points'] = '<span class="remain">'.$data['points'].'</span>';
      }
      $item_array['description'] = $data['description'];
      $item_array['balance'] = $data['balance'];
      $item_array['date'] = $data['date'];
      $return_datas[] = $item_array;
    }
    return $return_datas;
  }
  function prepare_items() {
    $this->_column_headers = $this->get_column_info();
    $per_page     = $this->get_items_per_page( 'customers_per_page', 50 );
    $current_page = $this->get_pagenum();
    $total_items  = 0;
    $args = array(
      'per_page' => $per_page,
      'paged' => $current_page,
    );
    if( isset( $_GET['user_name'] ) && !empty( trim($_GET['user_name']) ) ){
      $user = get_user_by( 'login', trim($_GET['user_name']) );
      if( !empty($user)){
        $args['user_id'] = $user->ID;
      }
    }
    if( isset( $_GET['action_name'] ) && !empty( trim($_GET['action_name']) ) ){
      if( in_array( $_GET['action_name'], array( 'add', 'reduce', 'remain' ) ) ){
        $args['action'] = $_GET['action_name'];
      }
    }
    $total_items  = ashuwp_count_points_activity($args);
    $datas = ashuwp_get_points_activity($args);
    $this->items = $this->format_activity($datas);
    $this->set_pagination_args( array(
      'total_items' => $total_items,
      'per_page'    => $per_page,
      'total_pages' => ceil($total_items/$per_page)
    ) );
  }
}
class ashuwp_points_activity_admin {
  static public $instance;
  public $points_activity_obj;
  private function __construct(){
    add_filter( 'set-screen-option', array( $this, 'set_screen' ), 10, 3 );
    add_action( 'admin_menu', array( $this, 'ashuwp_points_activity_menu') );
  }
  private function __clone() {
  }
  function ashuwp_points_activity_menu() {
    //svg图
    $dollor_ico = 'PHN2ZyB2ZXJzaW9uPSIxLjEiIGlkPSJFYmVuZV8xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4PSIwcHgiIHk9IjBweCIKCSB3aWR0aD0iMTAwcHgiIGhlaWdodD0iMTAwcHgiIHZpZXdCb3g9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3ZnPg==';
    //建立积分动态页面
    $hook = add_menu_page( 'Points Activity', 'Points Activity', 'manage_options', 'points_activity', array(&$this, 'points_activity_list'),'data:image/svg+xml;base64,'.$dollor_ico, 9);
    add_action( "load-$hook", array( $this, 'screen_option' ) );
  }
  function set_screen( $status, $option, $value ) {
    return $value;
  }
  function screen_option() {
    $option = 'per_page';
    $args   = array(
      'label'   => 'Customers',
      'default' => 30,
      'option'  => 'customers_per_page'
    );
    add_screen_option( $option, $args );
    $this->points_activity_obj = new Ashuwp_Points_Activity_Table();
  }
  function points_activity_list(){
    $all = ashuwp_count_points_activity();
    $points_add = ashuwp_count_points_activity( array( 'action'=>'add' ) );
    $points_reduce = ashuwp_count_points_activity( array( 'action'=>'reduce' ) );
    $points_remain = ashuwp_count_points_activity( array( 'action'=>'remain' ) );
  ?>
    <div class="wrap">
      <h1 class="wp-heading-inline">Points Activity</h1>
      <a href="<?php%20echo%20admin_url(%20'admin.php?page=points_activity_add'%20);%20?>" class="page-title-action">Add/Reduce</a>
      <?php
      if ( !  empty( $_GET['user_name'] ) ) { printf( ' ' .  __('Search results for "%s"') .  ' ', esc_html( $_GET['user_name'] ) ); } ?>  href=" ">All ( ) | href=" ">Add ( ) | href=" ">Reduce ( ) | href=" ">Remain ( )
        th.column-id,
        td.column-id,
        th.column-user,
        td.column-user,
        th.column-points,
        td.column-points,
        th.column-balance,
        td.column-balance {
          width:20%;
        }
        .column-points .add {
          color:#20b20;
        }
        .column-points .reduce {
          color:#e20c20c;
        }
        User Search  'search-submit') ); ?> points_activity_obj->prepare_items(); $this->points_activity_obj->display(); ?> 

2. User points page
Similar to the dynamic points page, the user points page also needs to be displayed in a table and not annotated one by one.

if(!class_exists('WP_List_Table')) { require_once( ABSPATH .  'wp-admin/includes/class-wp-list-table.php' );
}
class Ashuwp_User_Points_Table extends WP_List_Table {
  function __construct(){
    parent::__construct( array(
      'singular'  => 'User Points',
      'plural'    => 'User Points',
      'ajax'      => false
    ) );
  }
  function column_default( $item, $column_name ) {
    switch ( $column_name ){
      case 'user_id':
      case 'user_login':
      case 'points':
        return $item[ $column_name ];
      default:
        return print_r($item,true);
    }
  }
  function get_columns() {
    $columns = array(
      'user_id'       => 'User ID',
      'user_login'    => 'User Name',
      'points'      => 'Points',
    );
    return $columns;
  }
  function format_datas( $datas ) {
    $return_datas = array();
    foreach( $datas as $data ){
      $user = get_user_by('id', $data['user_id']);
      $item_array = array();
      $item_array['user_id'] = $data['user_id'];
      $item_array['user_login'] = $user->user_login;
      $item_array['points'] = $data['points'];
      $return_datas[] = $item_array;
    }
    return $return_datas;
  }
  function prepare_items() {
    $this->_column_headers = $this->get_column_info();
    $per_page     = $this->get_items_per_page( 'customers_per_page', 50 );
    $current_page = $this->get_pagenum();
    $total_items  = 0;
    $args = array(
      'per_page' => $per_page,
      'paged' => $current_page,
    );
    $total_items  = ashuwp_count_points();
    $datas = ashuwp_get_points($args);
    $this->items = $this->format_datas($datas);
    $this->set_pagination_args( array(
      'total_items' => $total_items,
      'per_page'    => $per_page,
      'total_pages' => ceil($total_items/$per_page)
    ) );
  }
}
class ashuwp_user_points_admin {
  static public $instance;
  public $user_points_obj;
  private function __construct(){
    add_filter( 'set-screen-option', array( $this, 'set_screen' ), 10, 3 );
    add_action( 'admin_menu', array( $this, 'ashuwp_user_points_menu') );
  }
  private function __clone() {
  }
  function ashuwp_user_points_menu() {
    $hook = add_submenu_page('points_activity', 'User Points', 'User Points', 'manage_options', 'user_points', array(&$this, 'user_points'));
    add_action( "load-$hook", array( $this, 'screen_option' ) );
  }
  function set_screen( $status, $option, $value ) {
    return $value;
  }
  function screen_option() {
    $option = 'per_page';
    $args   = array(
      'label'   => 'Customers',
      'default' => 30,
      'option'  => 'customers_per_page'
    );
    add_screen_option( $option, $args );
    $this->user_points_obj = new Ashuwp_User_Points_Table();
  }
  function user_points(){
    $all = ashuwp_count_points();
  ?>
    <div class="wrap">
      <h1 class="wp-heading-inline">User Points</h1>
      <a href="<?php%20echo%20admin_url(%20'admin.php?page=points_activity_add'%20);%20?>" class="page-title-action">Add/Reduce</a>
      <hr class="wp-header-end">
      <ul class="subsubsub">
        <li class="all"><a class="current" href="<?php%20echo%20admin_url(%20'admin.php?page=user_points'%20);%20?>">All<span class="count">(<?php echo $all; ?>)</span></a></li>
      </ul>
      <form id="points-activity-filter" method="get">
        <?php
        $this->user_points_obj->prepare_items();
        $this->user_points_obj->display();
        ?>
      </form>
    </div>
  <?php
  }
  public static function get_instance() {
    if ( ! 

3. Points increase and decrease page

if(!class_exists('WP_List_Table')) { require_once( ABSPATH .  'wp-admin/includes/class-wp-list-table.php' );
}
class Ashuwp_User_Points_Table extends WP_List_Table {
  function __construct(){
    parent::__construct( array(
      'singular'  => 'User Points',
      'plural'    => 'User Points',
      'ajax'      => false
    ) );
  }
  function column_default( $item, $column_name ) {
    switch ( $column_name ){
      case 'user_id':
      case 'user_login':
      case 'points':
        return $item[ $column_name ];
      default:
        return print_r($item,true);
    }
  }
  function get_columns() {
    $columns = array(
      'user_id'       => 'User ID',
      'user_login'    => 'User Name',
      'points'      => 'Points',
    );
    return $columns;
  }
  function format_datas( $datas ) {
    $return_datas = array();
    foreach( $datas as $data ){
      $user = get_user_by('id', $data['user_id']);
      $item_array = array();
      $item_array['user_id'] = $data['user_id'];
      $item_array['user_login'] = $user->user_login;
      $item_array['points'] = $data['points'];
      $return_datas[] = $item_array;
    }
    return $return_datas;
  }
  function prepare_items() {
    $this->_column_headers = $this->get_column_info();
    $per_page     = $this->get_items_per_page( 'customers_per_page', 50 );
    $current_page = $this->get_pagenum();
    $total_items  = 0;
    $args = array(
      'per_page' => $per_page,
      'paged' => $current_page,
    );
    $total_items  = ashuwp_count_points();
    $datas = ashuwp_get_points($args);
    $this->items = $this->format_datas($datas);
    $this->set_pagination_args( array(
      'total_items' => $total_items,
      'per_page'    => $per_page,
      'total_pages' => ceil($total_items/$per_page)
    ) );
  }
}
class ashuwp_user_points_admin {
  static public $instance;
  public $user_points_obj;
  private function __construct(){
    add_filter( 'set-screen-option', array( $this, 'set_screen' ), 10, 3 );
    add_action( 'admin_menu', array( $this, 'ashuwp_user_points_menu') );
  }
  private function __clone() {
  }
  function ashuwp_user_points_menu() {
    $hook = add_submenu_page('points_activity', 'User Points', 'User Points', 'manage_options', 'user_points', array(&$this, 'user_points'));
    add_action( "load-$hook", array( $this, 'screen_option' ) );
  }
  function set_screen( $status, $option, $value ) {
    return $value;
  }
  function screen_option() {
    $option = 'per_page';
    $args   = array(
      'label'   => 'Customers',
      'default' => 30,
      'option'  => 'customers_per_page'
    );
    add_screen_option( $option, $args );
    $this->user_points_obj = new Ashuwp_User_Points_Table();
  }
  function user_points(){
    $all = ashuwp_count_points();
  ?>
    <div class="wrap">
      <h1 class="wp-heading-inline">User Points</h1>
      <a href="<?php%20echo%20admin_url(%20'admin.php?page=points_activity_add'%20);%20?>" class="page-title-action">Add/Reduce</a>
      <hr class="wp-header-end">
      <ul class="subsubsub">
        <li class="all"><a class="current" href="<?php%20echo%20admin_url(%20'admin.php?page=user_points'%20);%20?>">All<span class="count">(<?php echo $all; ?>)</span></a></li>
      </ul>
      <form id="points-activity-filter" method="get">
        <?php
        $this->user_points_obj->prepare_items();
        $this->user_points_obj->display();
        ?>
      </form>
    </div>
  <?php
  }
  public static function get_instance() {
    if ( ! 

XNUMX. Practical application

When encountering an operation such as: successful recharge, successful purchase, and comment, execute the ashuwp_add_points_activity function.
Example XNUMX: Recharge successfully increases points.

//Prepare parameters $user_id = 1; //User id $points = 10; //Points $desc = 'Recharge:'.$points; $args = array( 'user_id' => $user_id, 'action' = > 'add', //Add 'points' => $points, 'description' => $desc, ); $chognzhi = ashuwp_add_points_activity($args);

V. Conclusion

The ideas and codes of this tutorial are for reference only. The code is stripped from the actual project by Ashu. In the process of code processing, there is no guarantee that there will be no errors, especially if there are two consecutive empty, please delete one by yourself.

Back to Top