Get subcategories with JSON API plugin

Retrieving terms

With the current version of the “WP API” (JSON API plugin), there’s a simple way to retrieve terms:

GET /taxonomies/<taxonomy>/terms

The method responsible is get_taxonomy_terms( $taxonomy ) in the plugins core.

You will have to check is_wp_error() on the return value to check if the taxonomy exists at the point where you invoke your own calls.

Internals

As we are talking about a new core API currently running as plugin, it sticks close to core itself and uses $terms = get_terms( $taxonomy, $args ); to retrieve the terms/taxons (categories, post tags, etc.) of a given taxonomy. The only default arg for that call is hide_empty => true.

Filtering the returned terms #1)

Looking at the core function internals, you will find a filter:

$args = apply_filters( 'get_terms_args', $args, $taxonomies );

So simply apply a callback to that filter. Be careful to not intercept other calls.

<?php
/** Plugin Name: (#163923) Alter term fetching args for the WP API/JSON plugin */

add_filter( 'get_terms_args', 'remote_parent_terms_from_json_response', 10, 2 );
function remote_parent_terms_from_json_response( Array $args, Array $taxonomies )
{
    // Do not impact subsequent calls and remove the callback. Single running filter cb.
    if ( /* some case */ )
    {
        remove_filter( current_filter(), __FUNCTION__ );

        return wp_parse_args( array(
            // alter args in here
        ), $args );
    }

    // default case
    return $args;
}

Filtering the returned terms #2)

Right after the call to the DB with get_terms(), the function loops through all fetched terms and “prepares” them for the JSONified return value using the prepare_taxonomy_term( $term ) method. This method has a filter at its very end:

return apply_filters( 'json_prepare_term', $data, $term, $context );

You could simply return FALSE or NULL if a taxonomy term does not fit in (for e.g. being a parent and having parent => 0 set) and then run array_filter( $terms ) on your returned data to remove all unset, false- or nullified terms.

This might be the easier solution that you want to use during prototyping. It as well is the more DB intensive solution as you first retrieve the terms from the DB and afterwards remove it, adding an additional overhead to your request.

Leave a Comment