Hướng dẫn tạo vote cho bài viết bằng cách sử dụng Ajax (ok)

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Ajax Wordpress</title>
</head>
<body>
	Hướng dẫn tạo vote bài viết bằng Ajax
	Bước 1: Bạn copy code vào file single.php
	<?php
		$tt = rand(1,100);
	   	$nonce = wp_create_nonce("my_user_vote_nonce");
	    $link = admin_url('admin-ajax.php?action=my_user_vote&post_id='.$post->ID.'&nonce='.$nonce.'&tt='.$tt);
	    echo '<a class="user_vote" data-nonce="' . $nonce . '" data-post_id="' . $post->ID . '" href="' . $link . '">vote for this article</a>';
	?>
	Giải thích một chút: 
	$nonce là chuỗi mã hóa nhận dạng giữa nơi gọi và nơi nhận cho sự kiện này, tránh hacker lợi dụng.
	(Bạn có thể đặt chuỗi my_user_vote_nonce thành tên khác miễn là bên file nhận tham số này phải trùng với chuỗi bạn đặt ban đầu)
	Bước 2: Bạn copy code vào file functions.php
	add_action("wp_ajax_my_user_vote", "my_user_vote");
	add_action("wp_ajax_nopriv_my_user_vote", "my_must_login");
	 
	function my_user_vote() {
	 	// Kiểm tra xem nếu không có thông báo tạo với tên my_user_vote_nonce thì hãy xuất ra thông báo
	   if ( !wp_verify_nonce( $_REQUEST['nonce'], "my_user_vote_nonce")) {
	      exit("No naughty business please");
	   }   
	 
	   $vote_count = get_post_meta($_REQUEST["post_id"], "votes", true);
	   $vote_count = ($vote_count == '') ? 0 : $vote_count;
	   $new_vote_count = $vote_count + 1;
	 
	   $vote = update_post_meta($_REQUEST["post_id"], "votes", $new_vote_count);
	 
	   if($vote === false) {
	      $result['type'] = "error";
	      $result['vote_count'] = $vote_count;
	   }
	   else {
	      $result['type'] = "success";
	      $result['vote_count'] = $new_vote_count;
	   }
	 	// Nếu truy xuất trực tiếp bằng trình duyệt thực hiện echo $result;
	   if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
	      $result = json_encode($result);
	      echo $result;
	   }
	   else {
	      header("Location: ".$_SERVER["HTTP_REFERER"]);
	   }
	 
	   die();
	 
	}
	 
	function my_must_login() {
	   echo "You must log in to vote";
	   die();
	}

</body>
</html>

Có thể tham thêm khảo ở đây

// ========= 

add_action('rest_api_init', 'register_api_hooks');
function register_api_hooks() {
  register_rest_route(
    'wp/v2', 'users/login',
    array(
      'methods'  => 'POST',
      'callback' => 'loginuser'
    )
  );
}
// function loginuser($request = null){
//   $creds = array();
//   echo '<pre>';
//     var_export($request);
//   echo '</pre>';
//   die();
//   $creds['user_login'] = $request["username"];
//   $creds['user_password'] =  $request["password"];
//   $creds['remember'] = true;
//   $user = wp_signon( $creds, false );
//   if ( is_wp_error($user) ) echo $user->get_error_message();
//   return $user;
// }
function loginuser($request = null) {
  $creds = array();
  $creds['user_login'] = $request["username"];
  $creds['user_password'] =  $request["password"];
  $creds['remember'] = true;
  $user = wp_signon( $creds, false );
  // if ( is_wp_error($user) ) echo $user->get_error_message();
  // $usernamepassword = $request["username"].":".$request["password"];
  // $pisa = new $request;
  // echo '<pre>';
  //   var_export($pisa['params']);
  // echo '</pre>';
  // die();
  // $wp_request_headers = array(
  //   'Authorization' => 'Basic ' . base64_encode( 'username:password'
  // );
  return $user;
}
function pointfinder_post_exists($id) {
  return is_string(get_post_status($id));
}
function pfcalculatefavs($user_id) {
  $user_favorites_arr = get_user_meta($user_id, 'user_favorites', true);
  $latest_fav_count   = $new_favorite_count   = $favorite_count   = 0;
  if (!empty($user_favorites_arr)) {
    $user_favorites_arr = json_decode($user_favorites_arr, true);
    $favorite_count     = count($user_favorites_arr);
    if (!empty($user_favorites_arr)) {
      foreach ($user_favorites_arr as $user_favorites_arr_single) {
        if (pointfinder_post_exists($user_favorites_arr_single)) {
          $new_user_fav_arr[] = $user_favorites_arr_single;
        }
      }
    }
  } else {
    $new_user_fav_arr = array('Không có sản phẩm nào yêu thích');
  }
  return $new_user_fav_arr;
}
// ==
add_action('rest_api_init', 'register_api_meta_fav');
function register_api_meta_fav() {
  register_rest_route(
    'wp/v2', 'users/metafavorites/(?P<id>[\d]+)',
    array(
      array(
        'methods'  => WP_REST_Server::READABLE,
        'callback' => 'usermetafavorites',
      ),
      array(
        'methods'  => WP_REST_Server::CREATABLE,
        'callback' => 'usercreatemetafavorites',
      ),
    )
  );
}
function usermetafavorites($request = null) {
  $user_id          = $request['id'] ? $request['id'] : 6;
  $new_user_fav_arr = pfcalculatefavs($user_id);
  return rest_ensure_response($new_user_fav_arr);
}
function usercreatemetafavorites($request = null) {
  $user_id          = $request['id'] ? $request['id'] : 6;
  $new_user_fav_arr = pfcalculatefavs($user_id);
  return rest_ensure_response($new_user_fav_arr);
}
// ==
add_action('rest_api_init', 'register_api_post_fav');
function register_api_post_fav() {
  register_rest_route(
    'wp/v2', 'users/postfavorites/(?P<id>[\d]+)',
    array(
      array(
        'methods'  => WP_REST_Server::READABLE,
        'callback' => 'userpostfavorites',
      ),
      array(
        'methods'  => WP_REST_Server::CREATABLE,
        'callback' => 'usercreatepostfavorites',
      ),
    )
  );
}
function userpostfavorites($request = null) {
  $id         = $request['id'] ? $request['id'] : '';
  $fav_number = get_post_meta($id, 'webbupointfinder_items_favorites', true);
  return $fav_number;
}
function usercreatepostfavorites($request = null) {
  $fav_item           = $request['id'] ? $request['id'] : '';
  $fav_check          = 'false';
  $user_ID            = get_current_user_id();
  $user_favorites_arr = json_decode(get_user_meta($user_ID, 'user_favorites', true));
  $fav_number         = get_post_meta($fav_item, 'webbupointfinder_items_favorites', true);
  if (is_user_logged_in() && count($user_favorites_arr) > 0) {
    if (in_array($fav_item, $user_favorites_arr)) {
      $fav_number = $fav_number - 1;
    } else {
      $fav_number = $fav_number + 1;
    }
    update_post_meta($fav_item, 'webbupointfinder_items_favorites', $fav_number);
    if (is_array($user_favorites_arr)) {
      $fav_item_pos = array_search($fav_item, $user_favorites_arr);
    } else {
      $fav_item_pos = false;
    }
  } else {
    $user_favorites_arr = array();
    $fav_item_pos       = false;
  }
  if ($fav_item_pos === false) {
    $user_favorites_arr[] = $fav_item;
    update_user_meta($user_ID, 'user_favorites', json_encode($user_favorites_arr));
  } else {
    if (!empty($user_favorites_arr)) {
      unset($user_favorites_arr[$fav_item_pos]);
    } else {
      $user_favorites_arr = array();
    }
    update_user_meta($user_ID, 'user_favorites', json_encode($user_favorites_arr));
  }
}
// =======
add_action('rest_api_init', 'register_api_get_parent_pointfinderltypes');
function register_api_get_parent_pointfinderltypes() {
  register_rest_route(
    'wp/v2', 'get_parent_pointfinderltypes',
    array(
      'methods'  => WP_REST_Server::READABLE,
      'callback' => 'get_parent_pointfinderltypes',
    )
  );
}
function get_parent_pointfinderltypes() {
  $taxonomies = array(
    'pointfinderltypes',
  );
  $args = array(
    'orderby' => 'name',
  );
  $terms   = get_terms($taxonomies, $args);
  $results = array();
  foreach ($terms as $term) {
    if ($term->parent === 0) {
      $results[] = $term;
    }
  }
  return rest_ensure_response($results);
}
// =======
add_action('rest_api_init', 'register_api_get_child_pointfinderltypes');
function register_api_get_child_pointfinderltypes() {
  register_rest_route(
    'wp/v2', 'get_child_pointfinderltypes/(?P<id>[\d]+)',
    array(
      'methods'  => WP_REST_Server::READABLE,
      'callback' => 'get_child_pointfinderltypes',
    )
  );
}
function get_child_pointfinderltypes($request = null) {
  $id         = $request['id'] ? $request['id'] : '';
  $taxonomies = array(
    'pointfinderltypes',
  );
  $args = array(
    'orderby' => 'name',
  );
  $terms   = get_terms($taxonomies, $args);
  $results = array();
  foreach ($terms as $term) {
    if ($term->parent !== 0 && $term->parent == $id) {
      $results[] = $term;
    }
  }
  return rest_ensure_response($results);
}
// =======
add_action('rest_api_init', 'register_api_get_all_cates');
function register_api_get_all_cates() {
  register_rest_route(
    'wp/v2', 'get_all_cates/',
    array(
      'methods'  => WP_REST_Server::READABLE,
      'callback' => 'get_all_cates',
    )
  );
}
function get_all_cates($request = null) {
  $taxonomies = array(
    'pointfinderltypes',
  );
  $args = array(
    'orderby' => 'count',
    'order'  => 'DESC',
  );
  $terms   = get_terms($taxonomies, $args);
  $results = array();
  foreach ($terms as $term) {
    $temp['cat_id'] = $term->term_id;
    $temp['cat_name'] = $term->name;
    $results[] = $temp;
  }
  return rest_ensure_response($results);
}
// =======
add_action('rest_api_init', 'register_api_get_all_city');
function register_api_get_all_city() {
  register_rest_route(
    'wp/v2', 'get_all_city/',
    array(
      'methods'  => WP_REST_Server::READABLE,
      'callback' => 'get_all_city',
    )
  );
}
function get_all_city($request = null) {
  $taxonomies = array(
    'pointfinderlocations',
  );
  $args = array(
    'orderby' => 'count',
    'order'  => 'DESC',
  );
  $terms   = get_terms($taxonomies, $args);
  $results = array();
  foreach ($terms as $term) {
    $temp['cit_id'] = $term->term_id;
    $temp['cit_name'] = $term->name;
    $results[] = $temp;
  }
  return rest_ensure_response($results);
}
// ===
add_action('rest_api_init', 'register_api_get_parent_id_pointfinderltypes');
function register_api_get_parent_id_pointfinderltypes() {
  register_rest_route(
    'wp/v2', 'get_parent_id_pointfinderltypes',
    array(
      'methods'  => WP_REST_Server::READABLE,
      'callback' => 'get_parent_id_pointfinderltypes',
    )
  );
}
function get_parent_id_pointfinderltypes() {
  $array = $terms = array();
  $arrayall = array(105,757,705,620,721,671,102,605,625,673,683,665,100,853,838,978,917,703,101,587,706,668,731,533,103,648,765,653,732,736,106,773,645,609,610,762,107,666,676,590,758,709,108,636,811,756,612,672,109,568,696,686,603,563,110,631,558,595,545,651,112,761,677,659,669,586,111,640,713,704,526,694);
    foreach ($arrayall as $value) {
      switch ($value) {
        case 105:
        $terms[0]['parent'] = get_term_by( 'id', 105, 'pointfinderltypes' );
        $arraychild = array(757,705,620,721,671);
        foreach ($arraychild as  $value) {
          $terms[0]['child'][] = get_term_by( 'id', 105, 'pointfinderltypes' );
        }
        case 102:
        $terms[1]['parent'] = get_term_by( 'id', 102, 'pointfinderltypes' );
        $arraychild = array(605,625,673,683,665);
        foreach ($arraychild as  $value) {
          $terms[1]['child'][] = get_term_by( 'id', 102, 'pointfinderltypes' );
        }
        case 100:
        $terms[2]['parent'] = get_term_by( 'id', 100, 'pointfinderltypes' );
        $arraychild = array(853,838,978,917,703);
        foreach ($arraychild as  $value) {
          $terms[2]['child'][] = get_term_by( 'id', 100, 'pointfinderltypes' );
        }
        case 101:
        $terms[3]['parent'] = get_term_by( 'id', 101, 'pointfinderltypes' );
        $arraychild = array(587,706,668,731,533);
        foreach ($arraychild as  $value) {
          $terms[3]['child'][] = get_term_by( 'id', 101, 'pointfinderltypes' );
        }
        case 103:
        $terms[4]['parent'] = get_term_by( 'id', 103, 'pointfinderltypes' );
        $arraychild = array(648,765,653,732,736);
        foreach ($arraychild as  $value) {
          $terms[4]['child'][] = get_term_by( 'id', 103, 'pointfinderltypes' );
        }case 106:
        $terms[5]['parent'] = get_term_by( 'id', 106, 'pointfinderltypes' );
        $arraychild = array(773,645,609,610,762);
        foreach ($arraychild as  $value) {
          $terms[5]['child'][] = get_term_by( 'id', 106, 'pointfinderltypes' );
        }case 107:
        $terms[6]['parent'] = get_term_by( 'id', 107, 'pointfinderltypes' );
        $arraychild = array(666,676,590,758,709);
        foreach ($arraychild as  $value) {
          $terms[6]['child'][] = get_term_by( 'id', 107, 'pointfinderltypes' );
        }case 108:
        $terms[7]['parent'] = get_term_by( 'id', 108, 'pointfinderltypes' );
        $arraychild = array(636,811,756,612,672);
        foreach ($arraychild as  $value) {
          $terms[7]['child'][] = get_term_by( 'id', 108, 'pointfinderltypes' );
        }case 109:
        $terms[8]['parent'] = get_term_by( 'id', 109, 'pointfinderltypes' );
        $arraychild = array(568,696,686,603,563);
        foreach ($arraychild as  $value) {
          $terms[8]['child'][] = get_term_by( 'id', 109, 'pointfinderltypes' );
        }case 110:
        $terms[9]['parent'] = get_term_by( 'id', 110, 'pointfinderltypes' );
        $arraychild = array(631,558,595,545,651);
        foreach ($arraychild as  $value) {
          $terms[9]['child'][] = get_term_by( 'id', 110, 'pointfinderltypes' );
        }case 112:
        $terms[10]['parent'] = get_term_by( 'id', 112, 'pointfinderltypes' );
        $arraychild = array(761,677,659,669,586);
        foreach ($arraychild as  $value) {
          $terms[10]['child'][] = get_term_by( 'id', 112, 'pointfinderltypes' );
        }case 111:
        $terms[11]['parent'] = get_term_by( 'id', 111, 'pointfinderltypes' );
        $arraychild = array(640,713,704,526,694);
        foreach ($arraychild as  $value) {
          $terms[11]['child'][] = get_term_by( 'id', 111, 'pointfinderltypes' );
        }
      }
    }
  return rest_ensure_response($terms);
}
// ====
add_action('rest_api_init', 'register_post_viewed_pointfinderltypes');
function register_post_viewed_pointfinderltypes() {
  register_rest_route(
    'wp/v2', 'get_post_viewed/(?P<id>[\d]+)',
    array(
      'methods'  => WP_REST_Server::READABLE,
      'callback' => 'get_post_viewed_pointfinderltypes',
    )
  );
}
function get_post_viewed_pointfinderltypes($request = null) {
  $wp_request_headers = array(
      'Authorization' => 'Basic ' . base64_encode( 'wordpress:wordpress' )
    );
  $wp_request_url = 'https://app.yp.vn/wp-json/wp/v2/posts/'.$request['id'];
  $wp_delete_post_response = wp_remote_request(
      $wp_request_url,
      array(
        'method'    => 'GET',
        'headers'   => $wp_request_headers
      )
  );
  wp_remote_retrieve_response_code( $wp_delete_post_response );
  wp_remote_retrieve_response_message( $wp_delete_post_response );
  $getpostmeta = 0;
  $current_user_id = get_current_user_id();
  if($current_user_id !=0) {
    $currentuseridpost = $current_user_id . '_' . $request['id'];
    $getpostmeta = get_post_meta($request['id'],$currentuseridpost,true);
  }
  return rest_ensure_response($getpostmeta);
}
function post_featured_image_json( $data, $post, $context ) {
  $get_theterms = get_post_meta($post->ID); 
  // $args = array(
  //   'post_type' => 'listing',  
  //   'post__not_in' => array($post->ID),
  //   'tax_query' => array(                     //(array) - Lấy bài viết dựa theo taxonomy
  //     array(
  //       'taxonomy' => 'pointfinderltypes',                //(string) - Tên của taxonomy
  //       'field' => 'id',                    //(string) - Loại field cần xác định term của taxonomy, sử dụng 'id' hoặc 'slug'
  //       'terms' => array( $get_theterms[0]->term_id ),    //(int/string/array) - Slug của các terms bên trong taxonomy cần lấy bài
  //       'include_children' => false,           //(bool) - Lấy category con, true hoặc false
  //       'operator' => 'IN'                    //(string) - Toán tử áp dụng cho mảng tham số này. Sử dụng 'IN' hoặc 'NOT IN'
  //     )
  //   )
  // );
  // $query = new WP_Query($args);
  // $mydata = unserialize($get_theterms['webbupointfinder_item_custom_marker'][0]);
  // $data->data['mydata'] = $mydata;
  $data->data['featured_image_url'] = wp_get_attachment_url(get_post_thumbnail_id($post->ID),'full');
  // $data->data['webbupointfinder_items_address'] = get_the_terms($post->ID,'pointfinderltypes');
  $data->data['webbupointfinderitemsaddress'] = $get_theterms['webbupointfinder_items_address'];
  $data->data['webbupointfinderitemslocation'] = $get_theterms['webbupointfinder_items_location'];
  $data->data['webbupointfinderitemfieldtelephone'] = $get_theterms['webbupointfinder_item_field_telephone'];
  $data->data['webbupointfinderitemfieldmobile'] = $get_theterms['webbupointfinder_item_field_mobile'];
  $data->data['webbupointfinderitemfieldemail'] = $get_theterms['webbupointfinder_item_field_email'];
  $data->data['webbupointfinderitemfieldwebsite'] = $get_theterms['webbupointfinder_item_field_website'];
  $data->data['webbupointfinderitemcustommarker'] = unserialize($get_theterms['webbupointfinder_item_custom_marker'][0]);
  $data->data['webbupointfinderitemheaderimage'] = unserialize($get_theterms['webbupointfinder_item_headerimage'][0]);
  $data->data['webbupointfinderitemsliderimage'] = unserialize($get_theterms['webbupointfinder_item_sliderimage'][0]);
  // $tags = get_the_tags();
  // $tagall   = [];
  // $countarr = count($tags);
  // foreach ($tags as $key => $value) {
  //   $tagall[] = $tags[$key]->term_id;
  // }
  // $args = array(
  //   'tag__in'          => $tagall,
  //   'post__not_in'     => array($post->ID),
  //   'posts_per_page'   => 5,
  //   'caller_get_posts' => 1,
  // );
  // $my_query = new WP_Query($args);
  // $data->data['realatexposts'] = $my_query;
  return $data;
}
add_filter( 'rest_prepare_post', 'post_featured_image_json', 10, 3 );
// ==========
function get_parentpointfinderltypes() {
  $array = $terms = array();
  $arrayall = array(105,102,100,101,103,106,107,108,109,110,112,111);
    foreach ($arrayall as $value) {
      switch ($value) {
        case 105:
        $terms[0]['parent'] = get_term_by( 'id', 105, 'pointfinderltypes' );
        $arraychild = array(757,705,620,721,671);
        foreach ($arraychild as  $value) {
          $terms[0]['child'][] = get_term_by( 'id', 105, 'pointfinderltypes' );
        }
        case 102:
        $terms[1]['parent'] = get_term_by( 'id', 102, 'pointfinderltypes' );
        $arraychild = array(605,625,673,683,665);
        foreach ($arraychild as  $value) {
          $terms[1]['child'][] = get_term_by( 'id', 102, 'pointfinderltypes' );
        }
        case 100:
        $terms[2]['parent'] = get_term_by( 'id', 100, 'pointfinderltypes' );
        $arraychild = array(853,838,978,917,703);
        foreach ($arraychild as  $value) {
          $terms[2]['child'][] = get_term_by( 'id', 100, 'pointfinderltypes' );
        }
        case 101:
        $terms[3]['parent'] = get_term_by( 'id', 101, 'pointfinderltypes' );
        $arraychild = array(587,706,668,731,533);
        foreach ($arraychild as  $value) {
          $terms[3]['child'][] = get_term_by( 'id', 101, 'pointfinderltypes' );
        }
        case 103:
        $terms[4]['parent'] = get_term_by( 'id', 103, 'pointfinderltypes' );
        $arraychild = array(648,765,653,732,736);
        foreach ($arraychild as  $value) {
          $terms[4]['child'][] = get_term_by( 'id', 103, 'pointfinderltypes' );
        }case 106:
        $terms[5]['parent'] = get_term_by( 'id', 106, 'pointfinderltypes' );
        $arraychild = array(773,645,609,610,762);
        foreach ($arraychild as  $value) {
          $terms[5]['child'][] = get_term_by( 'id', 106, 'pointfinderltypes' );
        }case 107:
        $terms[6]['parent'] = get_term_by( 'id', 107, 'pointfinderltypes' );
        $arraychild = array(666,676,590,758,709);
        foreach ($arraychild as  $value) {
          $terms[6]['child'][] = get_term_by( 'id', 107, 'pointfinderltypes' );
        }case 108:
        $terms[7]['parent'] = get_term_by( 'id', 108, 'pointfinderltypes' );
        $arraychild = array(636,811,756,612,672);
        foreach ($arraychild as  $value) {
          $terms[7]['child'][] = get_term_by( 'id', 108, 'pointfinderltypes' );
        }case 109:
        $terms[8]['parent'] = get_term_by( 'id', 109, 'pointfinderltypes' );
        $arraychild = array(568,696,686,603,563);
        foreach ($arraychild as  $value) {
          $terms[8]['child'][] = get_term_by( 'id', 109, 'pointfinderltypes' );
        }case 110:
        $terms[9]['parent'] = get_term_by( 'id', 110, 'pointfinderltypes' );
        $arraychild = array(631,558,595,545,651);
        foreach ($arraychild as  $value) {
          $terms[9]['child'][] = get_term_by( 'id', 110, 'pointfinderltypes' );
        }case 112:
        $terms[10]['parent'] = get_term_by( 'id', 112, 'pointfinderltypes' );
        $arraychild = array(761,677,659,669,586);
        foreach ($arraychild as  $value) {
          $terms[10]['child'][] = get_term_by( 'id', 112, 'pointfinderltypes' );
        }case 111:
        $terms[11]['parent'] = get_term_by( 'id', 111, 'pointfinderltypes' );
        $arraychild = array(640,713,704,526,694);
        foreach ($arraychild as  $value) {
          $terms[11]['child'][] = get_term_by( 'id', 111, 'pointfinderltypes' );
        }
      }
    }
  return $terms;
}
// ==
add_action('rest_api_init', 'register_api_app_post_fav');
function register_api_app_post_fav() {
  register_rest_route(
    'wp/v2', 'users/app_postfavorites/(?P<id>[\d]+)/(?P<id_user>[\d]+)',
    array(
      array(
        'methods'  => WP_REST_Server::READABLE,
        'callback' => 'appuserpostfavorites',
      ),
      array(
        'methods'  => WP_REST_Server::CREATABLE,
        'callback' => 'appusercreatepostfavorites',
      ),
    )
  );
}
function appuserpostfavorites($request = null) {
  $id         = $request['id'] ? $request['id'] : '';
  $fav_number = get_post_meta($id, 'webbupointfinder_items_favorites', true);
  return $fav_number;
}
function appusercreatepostfavorites($request = null) {
  $fav_item           = $request['id'] ? $request['id'] : '';
  $fav_check          = 'false';
  $user_ID            = $request['id_user'] ? $request['id_user'] : '';
  // echo $user_ID;
  // die();
  // $user_favorites_arr = json_decode(get_user_meta($user_ID, 'user_favorites', true));
  $user_favorites_arr = pfcalculatefavs($user_ID);
  // var_dump($user_favorites_arr);
  // die();
  $fav_number         = get_post_meta($fav_item, 'webbupointfinder_items_favorites', true);
  // var_dump($fav_number);
  // die();
  if (count($user_favorites_arr) > 0) {
    if (in_array($fav_item, $user_favorites_arr)) {
      $fav_number = $fav_number - 1;
    } else {
      $fav_number = $fav_number + 1;
    }
    update_post_meta($fav_item, 'webbupointfinder_items_favorites', $fav_number);
    if (is_array($user_favorites_arr)) {
      $fav_item_pos = array_search($fav_item, $user_favorites_arr);
    } else {
      $fav_item_pos = false;
    }
    // var_dump($fav_item_pos);
    // die();
  } else {
    $user_favorites_arr = array();
    $fav_item_pos       = false;
  }
  if ($fav_item_pos === false) {
    // var_dump($user_favorites_arr);
    $user_favorites_arr[] = $fav_item;
    // echo "abc";
    // var_dump($user_favorites_arr);
    // die();
    $result = update_user_meta($user_ID, 'user_favorites', json_encode($user_favorites_arr));
    if ($result){
      $res = array();
      $res['kq'] = true;
      $res['message'] = "Thêm công ty yêu thích thành công";
      return rest_ensure_response($res);
    } else {
      $res = array();
      $res['kq'] = false;
      $res['message'] = "Thêm công ty yêu thích thất bại";
      return rest_ensure_response($res);
    }
  } else {
    if (!empty($user_favorites_arr)) {
      unset($user_favorites_arr[$fav_item_pos]);
    } else {
      $user_favorites_arr = array();
    }
    update_user_meta($user_ID, 'user_favorites', json_encode($user_favorites_arr));
    $res = array();
    $res['kq'] = true;
    $res['message'] = "Xóa công ty yêu thích thành công";
    return rest_ensure_response($res);
  }
}
// ===========
add_action('rest_api_init', 'popularpost_post_view');
function popularpost_post_view() {
  register_rest_route(
    'wp/v2', 'popularpost_post_view',
    array(
      'methods'  => WP_REST_Server::READABLE,
      'callback' => 'callbackpopularpost_post_view',
    )
  );
}
function callbackpopularpost_post_view() {
  $popularposts = new WP_Query(
    array(
      'posts_per_page' => 5,
      'post_type'      => 'listing',
      'meta_key'       => 'webbupointfinder_page_itemvisitcount',
      'orderby'        => 'meta_value_num',
      'order'          => 'DESC',
    )
  );
  $posts = $popularposts->posts;
  $postsarr = [];
  foreach ($posts as $key => $post) {
    $post->views = get_post_meta($post->ID,'webbupointfinder_page_itemvisitcount')[0];
    $post->featured_image = wp_get_attachment_url(get_post_thumbnail_id($post->ID),'full');
    $postsarr[] = $post;
  }
  return rest_ensure_response($postsarr);
}
// =======
add_action('rest_api_init', 'register_api_get_home_cate');
function register_api_get_home_cate() {
  register_rest_route(
    'wp/v2', 'get_home_cate/',
    array(
      'methods'  => WP_REST_Server::READABLE,
      'callback' => 'get_home_cate',
    )
  );
}
function get_home_cate($request = null) {
  $id         = $request['id'] ? $request['id'] : '';
  $taxonomies = array(
    'pointfinderltypes',

  );
  $args = array(
    'orderby' => 'name',
    'child_of' => 0,
    'parent' => 0,
  );
  $terms   = get_terms($taxonomies, $args);
  $results = array();
  foreach ($terms as $term) {
    $parent = array();
    $parent['item'] = $term;
    $args_child = array(
      'taxonomy' => 'pointfinderltypes',
      'orderby' => 'count',
      'order'  => 'DESC',
      'number'  => '5',
      'child_of' => $term->term_id,
    );
    $parent['children'] = get_terms($args_child);
    $results[] = $parent;
  }
  return rest_ensure_response($results);
}
// =======
add_action('rest_api_init', 'register_api_get_parent_cate');
function register_api_get_parent_cate() {
  register_rest_route(
    'wp/v2', 'get_parent_cate/',
    array(
      'methods'  => WP_REST_Server::READABLE,
      'callback' => 'get_parent_cate',
    )
  );
}
function get_parent_cate() {
  $args = array(
    'taxonomy' => 'pointfinderltypes',
    'orderby' => 'name',
    'child_of' => 0,
    'parent' => 0,
  );
  $terms   = get_terms($args);
  return rest_ensure_response($terms);
}

add_action('rest_api_init', 'wp_rest_user_endpoints');
/**
 * Register a new user
 *
 * @param  WP_REST_Request $request Full details about the request.
 * @return array $args.
 **/
function wp_rest_user_endpoints($request) {
  /**
   * Handle Register User request.
   */
  register_rest_route('wp/v2', 'users/register', array(
    'methods' => 'POST',
    'callback' => 'wc_rest_user_endpoint_handler',
  ));
}
function wc_rest_user_endpoint_handler($request = null) {
  $response = array();
  $parameters = $request->get_json_params();
  $username = sanitize_text_field($parameters['username']);
  $email = sanitize_text_field($parameters['email']);
  $password = sanitize_text_field($parameters['password']);
  // $role = sanitize_text_field($parameters['role']);
  $error = new WP_Error();
  if (empty($username)) {
    $error->add(400, __("Username field 'username' is required.", 'wp-rest-user'), array('status' => 400));
    return $error;
  }
  if (empty($email)) {
    $error->add(401, __("Email field 'email' is required.", 'wp-rest-user'), array('status' => 400));
    return $error;
  }
  if (empty($password)) {
    $error->add(404, __("Password field 'password' is required.", 'wp-rest-user'), array('status' => 400));
    return $error;
  }
  // if (empty($role)) {
  //  $role = 'subscriber';
  // } else {
  //     if ($GLOBALS['wp_roles']->is_role($role)) {
  //      // Silence is gold
  //     } else {
  //    $error->add(405, __("Role field 'role' is not a valid. Check your User Roles from Dashboard.", 'wp_rest_user'), array('status' => 400));
  //    return $error;
  //     }
  // }
  $user_id = username_exists($username);
  if (!$user_id && email_exists($email) == false) {
    $user_id = wp_create_user($username, $password, $email);
    if (!is_wp_error($user_id)) {
      // Ger User Meta Data (Sensitive, Password included. DO NOT pass to front end.)
      $user = get_user_by('id', $user_id);
      // $user->set_role($role);
      $user->set_role('subscriber');
      // WooCommerce specific code
      if (class_exists('WooCommerce')) {
        $user->set_role('customer');
      }
      // Ger User Data (Non-Sensitive, Pass to front end.)
      $response['code'] = 200;
      $response['message'] = __("User '" . $username . "' Registration was Successful", "wp-rest-user");
    } else {
      return $user_id;
    }
  } else {
    $error->add(406, __("Email already exists, please try 'Reset Password'", 'wp-rest-user'), array('status' => 400));
    return $error;
  }
  return new WP_REST_Response($response, 123);
}

Last updated