Categories

Friday, November 22, 2024
#919814419350 therichposts@gmail.com
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:

https://www.sitelink/wp-json/wp/v2/custpost

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.

Jassa

Thanks

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 19, MedusaJs, Next.js, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

2 Comments

Leave a Reply

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