Search code examples
phpwordpresswordpress-themingcustom-wordpress-pageswordpress-rest-api

Wordpress how to get specific post data using WP_REST_Posts_Controller


How I can get specific post data in foreach loop? (only title for example)

Here is my PHP (returns all post data):

function myspace_get_posts_by_tag(WP_REST_Request $request) {
    
    $slug = $request['slug'];
    $page = $request['page'];

    $term = get_term_by('slug', $slug, 'post_tag');
    $posts_per_page = 1;

    $args = array(
        'tag__in'           => $term->term_id,
        'posts_per_page'    => $posts_per_page,
        'paged'             => $page,
        'orderby'           => 'date',
        'order'             => 'desc',
    );

    $query = new WP_Query( $args ); 

    $max_pages = $query->max_num_pages;
    $total = $query->found_posts;

    $posts = $query->posts;

    $controller = new WP_REST_Posts_Controller('post');

    foreach ( $posts as $post ) {

        $response = $controller->prepare_item_for_response( $post, $request );
        $data[] = $controller->prepare_response_for_collection( $response );            

    }
   
    $response = new WP_REST_Response($data, 200);
    $response->header( 'X-WP-Total', $total ); 
    $response->header( 'X-WP-TotalPages', $max_pages );
    return $response;
    
}

I cut down some code just for the sake of example.


Solution

  • You are using WP_Query() to fetch the posts later in the foreach loop.

    In that case, $post is a WP_Post Object. So you can access its properties, in your case - the post's title:

    $post->post_title