Last active
January 31, 2016 12:20
-
-
Save hungdh0x5e/d159d91977812516c0f5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Plugin Name: REST API Custom | |
Plugin URI: http://hungdh.me | |
Description: Add metadata, end point to the REST API | |
Author: Huy Hung | |
Version: 1.0 | |
Author URI: http://hungdh.me | |
*/ | |
/** | |
* | |
* Thêm api lấy danh sách bài viết theo category | |
* Querry: /wp-json/wp/v2/get_category_posts/cat=2&page=1/ | |
*/ | |
add_action( 'rest_api_init', 'hdh_register_end_point_category' ); | |
function hdh_register_end_point_category() { | |
register_rest_route( 'wp/v2', '/get_category_posts/cat=(?P<cat_id>\d+)&page=(?P<page_id>\d+)', | |
array( | |
'methods' => 'GET', | |
'callback' => 'hdh_getPostByCategory', | |
) ); | |
} | |
function hdh_getPostByCategory($data){ | |
wp_reset_postdata(); | |
wp_reset_query(); | |
$category = get_category($data['cat_id']); | |
$cate['id'] = $category->cat_ID; | |
$cate['name'] = $category->name; | |
$cate['slug'] = $category->slug; | |
$cate['description'] = $category->category_description; | |
$cate['total'] = $category->category_count; | |
$pages = intval($cate['total'] / 10); | |
if($pages*10 != $cate['total']) | |
$pages++; | |
$cate['pages'] = $pages; | |
if($data['page_id'] > $pages){ | |
$cate['count'] = 0; | |
return $cate; | |
} | |
$query = array( | |
'offset' => ($data['page_id']-1)*10, | |
'posts_per_page' => 10, | |
'cat' => $data['cat_id'], | |
'orderby'=> 'date', | |
'order' => 'des' | |
); | |
$list_posts = array(); | |
$cf = new WP_Query($query); | |
$count = 0; | |
while ($cf->have_posts()) : $cf->the_post(); | |
$post['id'] = get_the_ID(); | |
$post['title']['rendered'] = get_the_title(); | |
$post['link'] = get_the_permalink(); | |
$post['thumbnail'] = wp_get_attachment_url(get_post_thumbnail_id(get_the_ID())); | |
$post['post_views_count'] = intval(trim(get_post_meta( get_the_ID(), 'post_views_count', true ))); | |
$post['status'] = trim(get_post_meta(get_the_ID(), 'status', true)); | |
$post['chapter_count'] = intval(trim(get_post_meta(get_the_ID(), 'chapter_count', true))); | |
$count++; | |
array_push($list_posts, $post); | |
endwhile; | |
wp_reset_postdata(); | |
$cate['count'] = $count; | |
$cate['posts'] = $list_posts; | |
return $cate; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment