Show popular post in another php website via WP REST JSON API

I will give you a small answer to your update, doing this with the WP API.
The API have the possibilities to use the WP_Query like also in core, but about the get parameters in the url.

A URL to pull content from Post Status would look like this:

http://example.com/wp-json/posts

To pull content with WP_Query parameters you’re used to, you could do it like this:

http://example.com/wp-json/posts?filter[posts_per_page]=2&filter[order]=ASC

You can build your custom query with all parameters also in the url. You can see how the method for grabbing that data feels familiar to using WP_Query for a standard WordPress loop. If you don’t specify a parameter, the defaults to WP_Query will be used.

The result is json, that you can parse and use for you external site.

See also the site of the API for more parameters and documentation.

Update for date_query

The API can’t create a result for a query like query_date. See the documentation for all possible parameters.

But the new version will release in view days, weeks. And see this issue for discussion about a solution for this date query. Alternative use a custom filter via hook, like:

// Allow datequery in /posts filter
add_filter( "json_query_vars", function( $query_args ) {
    return array_merge( $query_args, 
        array( "date_query" => array( array( "after" => "1 week ago" ) ) )
    );
} );

Update for meta_query

The API can’t also this feature of the default WP-Query. But you can use a hook to enhance the API to this requirement. Also here a small example.

add_filter('json_query_var-meta_query', 'add_meta_query', 10, 1);

function add_meta_query( $data ){

    $args = array();
    $args['relation'] = 'AND';

    foreach ( $data as $key => $value ) {
        if ( 'relation' === $key ) {
            $args['relation'] = $data['relation'];
        }

        if ( substr($key, 0, 3) === 'key' ) {
            $arg_num = substr( $key, 3 );
            $args[ (int) $arg_num ][ 'key' ] = $value;
        }

        if (  substr( $key, 0, 7 ) === 'compare' ) {
            $arg_num_comp = substr( $key, 7 );
            $args[ (int) $arg_num_comp ][ 'compare' ] = $value;
        }
    }

    return $args;
}

Now, I can call JSON restful like that to mimic the Wp_query posts filter already on the server:

?filter[meta_query][key]=_newsml_categories_newsstream&filter[meta_query][key2]=homepage&filter[meta_query][relation]=AND&filter[meta_query][compare]=NOT%20EXISTS&filter[meta_query][compare2]=NOT%20EXISTS

The meta query update based from this answer.

Leave a Comment