Learn how to filter WordPress REST API posts by custom meta key and value, enabling you to retrieve content based on specific metadata.
Enable Meta Query Filtering in WordPress REST API
To filter WordPress REST API posts by a custom meta key and value, add custom code to your WordPress installation to enable meta query filtering.
Step 1: Add Custom Code to Your Theme or Plugin
Add the following PHP code snippet to your theme’s functions.php
file or in a custom plugin to allow meta query filtering in the WordPress REST API:
function allow_meta_query( $args, $request ) {
$meta_key = $request->get_param( 'meta_key' );
$meta_value = $request->get_param( 'meta_value' );
if ( ! empty( $meta_key ) && ! empty( $meta_value ) ) {
$args['meta_query'] = array(
array(
'key' => $meta_key,
'value' => $meta_value
)
);
}
return $args;
}
add_filter( 'rest_post_query', 'allow_meta_query', 10, 2 );
Step 2: Query the WordPress JSON API with Meta Key and Value
After adding the custom code, you can query the WordPress JSON API to get posts with a specific meta key and value. Send a GET request to the following URL:
https://your-wordpress-site.com/wp-json/wp/v2/posts?meta_key=foo&meta_value=bar
Replace your-wordpress-site.com
with the domain of your WordPress site and bar
with the desired value for the “foo” meta key. The API will return a JSON object containing the matching post(s) with the specified meta key and value.
Happy querying!