WordPress.org

Make WordPress Core


Ignore:
Timestamp:
05/26/2021 02:15:51 AM (6 months ago)
Author:
TimothyBlynJacobs
Message:

REST API: Add support for modifying the term relation when querying posts.

By default, a post most contain any of the requested terms to be included in the response. This commit adds a new operator property that can be set to AND to require a post to contain all of the requested terms.

For example, /wp/v2/posts?tags[terms]=1,2,3&tags[operator]=AND will return posts that have tags with the ids of 1, 2, and 3.

Props dlh, earnjam, Clorith, jnylen0, sebbb.
Fixes #41287.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tests/phpunit/tests/rest-api/rest-posts-controller.php

    r50717 r51026  
    12931293        $this->assertNotContains( $p1, $found_ids );
    12941294        $this->assertContains( $p2, $found_ids );
     1295    }
     1296
     1297    /**
     1298     * @ticket 41287
     1299     */
     1300    public function test_get_items_with_all_categories() {
     1301        $taxonomy   = get_taxonomy( 'category' );
     1302        $categories = static::factory()->term->create_many( 2, array( 'taxonomy' => $taxonomy->name ) );
     1303
     1304        $p1 = static::factory()->post->create(
     1305            array(
     1306                'post_status'   => 'publish',
     1307                'post_category' => array( $categories[0] ),
     1308            )
     1309        );
     1310        $p2 = static::factory()->post->create(
     1311            array(
     1312                'post_status'   => 'publish',
     1313                'post_category' => array( $categories[1] ),
     1314            )
     1315        );
     1316        $p3 = static::factory()->post->create(
     1317            array(
     1318                'post_status'   => 'publish',
     1319                'post_category' => $categories,
     1320            )
     1321        );
     1322
     1323        $request = new WP_REST_Request( 'GET', '/wp/v2/posts' );
     1324        $request->set_param(
     1325            $taxonomy->rest_base,
     1326            array(
     1327                'terms'    => $categories,
     1328                'operator' => 'AND',
     1329            )
     1330        );
     1331        $response = rest_get_server()->dispatch( $request );
     1332        $data     = $response->get_data();
     1333
     1334        $this->assertCount( 1, $data );
     1335        $this->assertSame( $p3, $data[0]['id'] );
    12951336    }
    12961337
Note: See TracChangeset for help on using the changeset viewer.