Skip to content

Instantly share code, notes, and snippets.

@reactmore
Last active August 19, 2021 09:07
Show Gist options
  • Save reactmore/79ddef0a4a5cb70a1871a14694bf2dcc to your computer and use it in GitHub Desktop.
Save reactmore/79ddef0a4a5cb70a1871a14694bf2dcc to your computer and use it in GitHub Desktop.
Custom route Wordpress API
add_action('rest_api_init', 'custom_api_get_all_posts');
function custom_api_get_all_posts()
{
register_rest_route('custom/v1', '/all-posts', array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'custom_api_get_all_posts_callback'
));
}
// custom Route API
function custom_api_get_all_posts_callback(WP_REST_Request $request)
{
// Initializearray untuk menerima Post data
$posts_data = array();
// Menerima Parameter Dari $request untuk melakukan paginations
$paged = $request->get_param('page');
$paged = (isset($paged) || !(empty($paged))) ? $paged : 1;
// Mengambil Semua data Posts dan postype dengan terbaru di awal (DESC)
$query = new WP_Query(
array(
'paged' => $paged,
'post__not_in' => get_option('sticky_posts'),
'posts_per_page' => 10,
'post_type' => array('post') // Type Post apa saja yang di ijinkan masuk.
)
);
// if no posts found return
if (empty($query->posts)) {
return new WP_Error('no_posts', __('No post found'), array('status' => 404));
}
// set max number of pages and total num of posts
$max_pages = $query->max_num_pages;
$total = $query->found_posts;
$posts = $query->posts;
// prepare data for output
$controller = new WP_REST_Posts_Controller('post');
foreach ($posts as $post) {
$response = $controller->prepare_item_for_response($post, $request);
$post_data = $controller->prepare_response_for_collection($response);
$post_thumbnail = (has_post_thumbnail($post_data['id'])) ? get_the_post_thumbnail_url($post_data['id']) : null;
$data[] = (object) array(
'id' => $post_data['id'],
'slug' => $post_data['title']['rendered'],
'date' => $post->post_date,
'author' => get_the_author_meta('user_nicename', $post->post_author),
'type' => $post->post_type,
'title' => $post->post_title,
'url' => get_permalink($post_data['id']),
'content' => $post_data['excerpt']['rendered'],
'featured_img_src' => $post_thumbnail,
'meta' => get_post_meta($post_data['id'], '', '')
);
}
// set headers and return response
$response = new WP_REST_Response($data, 200);
$response->header('X-WP-Total', $total);
$response->header('X-WP-TotalPages', $max_pages);
return $response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment