WordPress get_posts by title like

Nico Martin picture Nico Martin · Aug 3, 2014 · Viewed 31.4k times · Source

I am trying to create a small search-function for WordPress. An AJAX call should get all posts where the title is like %quote%.

Is there a possibility to make this happen inside the get_posts() function?

Don't get me wrong. The ajax works fine. I have the ajax function in my functions.php and I receive the posts. It's just the "where title like" part where I couldn't find a solution.

Answer

Bullyen picture Bullyen · Nov 10, 2014

You could do a custom search query also.

$search_query = "SELECT ID FROM {$wpdb->prefix}posts
                         WHERE post_type = 'post' 
                         AND post_title LIKE %s";
    
$like = '%'.$quote.'%';
$results = $wpdb->get_results($wpdb->prepare($search_query, $like), ARRAY_N);

$quote_ids = array_column($results, 'ID');

$quotes = get_posts(array('post_type'=>'post', 'orderby'=>'title', 'order'=>'ASC', 'post__in' => $quote_ids));