• Resolved especht

    (@especht)


    Our WP backend uses the REST API to search for articles to select for various sections. Currently the keywords that are used for search are compared against the body of the article, etc. Instead, we want it just to search on the article title.

    So I’ve made a custom argument that allows us to do that from PHP:

    add_filter( ‘posts_where’, function ( $where, \WP_Query $q )
    {
    global $wpdb;
    $query_by_title = $q->get( ‘queryByTitle’ );
    if ( $query_by_title = $q->get( ‘queryByTitle’ ) ) {
    $where .= ‘ AND ‘ . $wpdb->posts . ‘.post_title LIKE \” . esc_sql( $wpdb->esc_like( $query_by_title ) ) . ‘%\”;
    }
    return $where;

    }, 10, 2 );

    This works beautifully when called from PHP like this:

    $query = new WP_Query( array( ‘queryByTitle’ => ‘some phrase’ ) );

    How can I use the new queryByTitle argument via the REST API? I’ve tried this, but no luck:

    /wp-json/wp/v2/posts/?filter[queryByTitle]=some phrase

    Any ideas how a custom argument can be used with the WP REST Filter plugin?

Viewing 1 replies (of 1 total)
  • Thread Starter especht

    (@especht)

    I figured it out. To get this working, I needed to add the argument to rest_query_vars with this:

    function wpse_20160526_rest_query_vars( $valid_vars ) {
    $valid_vars = array_merge( $valid_vars, array( ‘queryByTitle’ ) );
    return $valid_vars;
    }

    add_filter( ‘rest_query_vars’, ‘wpse_20160526_rest_query_vars’, PHP_INT_MAX, 1 );

    After that, this URL worked:
    /wp-json/wp/v2/posts?filter[queryByTitle]=some-text

Viewing 1 replies (of 1 total)
  • The topic ‘how to filter using custom argument’ is closed to new replies.