BenB
BenB

Reputation: 2907

WP rest API get post by title

I'm trying to check by a post title if post exist or not. For some reason when i try something like:

http://domain.com/wp-json/wp/v2/posts?filter[post-title]=table

I want if post with the name table exist, to get the post, if not, get an empty response. But for some reason when post with title not exist i get all posts back. How could get empty when no post exist and the post when it exist.

Upvotes: 11

Views: 17615

Answers (4)

Jakyo
Jakyo

Reputation: 52

Update 2024

It's not well documented in the official Wordpress docs yet (https://developer.wordpress.org/rest-api/reference/posts/#arguments), but you can achieve a rest api search by post title with the combination of search and search_columns. search_columns is an enum, though, which I've noticed after trial & error, resulting in this error message:

search_columns[0] is not one of post_title, post_content and post_excerpt

Example, list all posts that contain "table" in their titles, and only in their titles:

http://example.com/wp-json/wp/v2/posts?search=table&search_columns=post_title

Upvotes: 2

Amin Ghazi
Amin Ghazi

Reputation: 75

You cannot do this through wp json, please copy the following code in the functions.php:

function __search_by_title_only( $search, &$wp_query ) {
    global $wpdb;

    if ( empty( $search ) )
        return $search; // skip processing - no search term in query

    $q = $wp_query->query_vars;    
    $n = ! empty( $q['exact'] ) ? '' : '%';

    $search =
    $searchand = '';

    foreach ( (array) $q['search_terms'] as $term ) {
        $term = esc_sql( like_escape( $term ) );
        $search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
        $searchand = ' AND ';
    }

    if ( ! empty( $search ) ) {
        $search = " AND ({$search}) ";
        if ( ! is_user_logged_in() )
            $search .= " AND ($wpdb->posts.post_password = '') ";
    }

    return $search;
}
add_filter( 'posts_search', '__search_by_title_only', 500, 2 );

Upvotes: 2

Black
Black

Reputation: 10397

Unfortunately it is not possible, but you can use slug instead. Slug is editable part of the URL when writing a post and they can represent title of the page (or it can be changed into this).

http://example.com/wp-json/wp/v2/posts?slug=table

More details: https://developer.wordpress.org/rest-api/reference/pages/#arguments

Upvotes: 11

Vasiu Alexandru
Vasiu Alexandru

Reputation: 123

According to http://v2.wp-api.org/, some have to use search keyword :
http://domain.com/wp-json/wp/v2/posts?search=table.

Upvotes: 5

Related Questions