5

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.

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Nico Martin
  • 1,268
  • 1
  • 14
  • 23

3 Answers3

13

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_A);

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

$quotes = get_posts(array('post_type'=>'post', 'orderby'=>'title', 'order'=>'ASC', 'post__in' => $quote_ids));
rkb
  • 514
  • 2
  • 9
  • 19
Bullyen
  • 808
  • 1
  • 8
  • 20
  • 1
    A bit late, but this saved me a couple of hours of researching. – Ciprian Jul 25 '15 at 20:15
  • `$results` needs to be an associative array (the second arg to `get_results` should be `ARRAY_A`) for `array_column($results, 'ID')` to return an array of IDs. – rkb Jan 01 '22 at 09:17
12

No, but you can create a custom loop.

Check this.

EDIT:

$args = array('s' => 'keyword');

$the_query = new WP_Query( $args );

// The Loop
if ( $the_query->have_posts() ) {
    
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        //whatever you want to do with each post
    }
} else {
     // no posts found
}   
ado387
  • 162
  • 1
  • 9
Tomás Cot
  • 992
  • 1
  • 8
  • 18
  • Please add the relevant information to your answer, because it's of no use if the link is goes down or changes. – birgire Aug 03 '14 at 13:57
  • Without doing the `while` can I just get a field from the post inside the `if` statement? – Si8 Jan 17 '18 at 15:11
  • @Si8. The ´if´ checks if the query has posts. Do you want to use this to get just one post? – Tomás Cot Jan 17 '18 at 16:33
  • I ended up using this: `$posts = $wp_query->posts;` rather than `while` which was causing the rest of my page to not generate. Thank you for the response. I +1 because your post helped me get in the right direction. – Si8 Jan 17 '18 at 17:34
4

Or you could use the filter posts_where like this:

$options = array(
    'posts_per_page' => -1,
    'suppress_filters' => false, // important!
    'post_type' => 'post',
    'post_status' => 'publish',
);
$keyword = 'quote';

add_filter( 'posts_where', 'my_filter_post_where' );
$posts = get_posts( $options );
remove_filter( 'posts_where', 'my_filter_post_where' );

function my_filter_post_where( $where) {
    global $wpdb;
    global $keyword;

    $where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( like_escape( $keyword ) ) . '%\'';

    return $where;
}
Mike
  • 533
  • 5
  • 4