Skip to content

Instantly share code, notes, and snippets.

@imCorfitz
Last active May 26, 2022 18:03
Show Gist options
  • Save imCorfitz/1e86b82d2edb81c788db3c8adac6746b to your computer and use it in GitHub Desktop.
Save imCorfitz/1e86b82d2edb81c788db3c8adac6746b to your computer and use it in GitHub Desktop.
Extend WP Rest API with `parent_category` param that includes posts from subcategories
<?php
// Add somewhere in functions.php for your child theme
// Add parent_category filter to REST API
if (!function_exists('wprabpc_wp_rest_api_by_parent_category')) {
function wprabpc_wp_rest_api_by_parent_category($args, $request)
{
if (isset($request['parent_category'])) {
$parent_category = sanitize_text_field($request['parent_category']);
$args['tax_query'] = [
[
'taxonomy' => 'category',
'field' => 'term_id',
'include_children' => true,
'operator' => 'IN',
'terms' => $parent_category,
],
];
}
return $args;
}
add_filter('rest_post_query', 'wprabpc_wp_rest_api_by_parent_category', 10, 3);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment