WordPress get_posts by title like

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?

Read More

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.

Related posts

Leave a Reply

3 comments

  1. 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));
    
  2. 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
    }   
    
  3. 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;
    }