Create filtered list of posts using JSON data

First, you must allow your custom field be queried from the REST API. Let’s start simple with an example from 1fix.io:

function my_allow_meta_query( $valid_vars ) {
    $valid_vars = array_merge( $valid_vars, array( 'meta_key', 'meta_value' ) );
    return $valid_vars;
}
add_filter( 'rest_query_vars', 'my_allow_meta_query' );

So, asuming your field name is called “favorite_animal”, for this example, you can query the posts using a filter url like this:

http://example.com/wp-json/wp/v2/posts/?filter[meta_key]=favorite_animal&filter[meta_value]=dog

I’d really recommend reading the linked post explaining the example code for your WordPress backend, since meta_key are by default allowed to used only by authenticated users and if you have private data in meta fields, the naive example given here it’s a security nightmare.

A simple way to consume the resources returned by the REST endpoint would be showing a list of posts, inside a widget for example, let’s assume a <div id="display"></div>

(function($) {
    $(function() {
        var resourceUrl="http://example.com/wp-json/wp/v2/posts/?filter[meta_key]=favorite_animal&filter[meta_value]=dog";
        $.get(resourceUrl,
            function(posts) {
                var output="";
                $.each(posts, function(index, post) {
                    output += '<p><a href="' + post.link + '">' + post.title.rendered.trim() + '</a></p>';
                });
                $('#display').html(output);
            }
        );
    });
})(jQuery);

Leave a Comment