Friday, October 22, 2021
Wordpresswordpress rest api

WordPress rest api to get custom post type posts

Wordpress rest api to get custom post type posts

Hello friends, welcome back to my blog and today in this blog post, I am going to tell you, WordPress Rest API to get custom post type posts.

Friends here is the working code snippet for WordPress rest API to get custom post type posts and please use this into your theme’s functions.php file:

add_action( 'rest_api_init', function () {
register_rest_route( 'wp/v2', '/cuspost/', array(
'methods' => 'GET',
'callback' => 'cuspost'
) );
} );

//callback function
function cuspost(){
   $args = array( 
    'post_type' => 'custom_post_type', 
    'post_status' => 'publish', 
    'nopaging' => true 
    $query = new WP_Query( $args ); // $query is the WP_Query Object
    $posts = $query->get_posts();   // $posts contains the post objects
    $output = array();
    foreach( $posts as $post ) {    // Pluck the id and title attributes
        $output[] = array( 'id' => $post->ID, 'title' => $post->post_title);
    wp_send_json( $output ); // getting data in json format.


2. API route will be:


Now we are done friends also and If you have any kind of query or suggestion or any requirement then feel free to comment below.

Note: Friends, I just tell the basic setup and things, you can change the code according to your requirements.

I will appreciate that if you will tell your views for this post. Nothing matters if your views will be good or bad.



Ajay Malhotra
the authorAjay Malhotra
Hello to all. Welcome to Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 2, Angular 6, Angular 7, Angular 8, Angular 9, Angular 10, Angular 11, Angular12, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.