Igor Simic
6 years ago

Wordpress REST API get posts by tag


How to extend Wordpress API to get list of posts by specific tag? In this example we will create custom route which will be triggered with tag url tag/my-tag and will return us list of posts for that specific tag order by date/desc. So first let's create custom route:
add_action( 'rest_api_init', function () {

          register_rest_route( 'myscope/v1/', 'get-by-tag/(?P<slug>[a-z0-9]+(?:-[a-z0-9]+)*)', array(
                'methods' => 'GET',
                'callback' => 'myscope_get_posts_by_tag',
                'args' => array(
                    'slug' => array (
                        'required' => false
                    ),
                    
                )
            ) );

        } );
Let's create function which will response to this URL. Here we will first get the tag id and other tag info and then select the posts from that tag. API request should look like this:
wp-json/myscope/v1/get-by-tag/my-tag
function myscope_get_posts_by_tag(WP_REST_Request $request){

            $slug = $request['slug'];

            // get tag object
            $term = get_term_by('slug', $slug, 'post_tag');
            /* term:
               [term_id] => 5
               [name] => My Tag
               [slug] => my-tag
               [term_group] => 0
               [term_taxonomy_id] => 5
               [taxonomy] => post_tag
               [description] => 
               [parent] => 0
               [count] => 1
               [filter] => raw
            */

            // let's get posts by this tag
            $args = array(
                'numberposts' => 5,
                'tag__in' => $term->term_id
            );
            $posts_by_tag = get_posts( $args );
            
            //return posts to api
            $response = new WP_REST_Response( $posts_by_tag);
  
            return $response;
        }