1

Is it possible to query posts by a specific word on title?

Example:

I have 3 posts inside my blog and only two have the word car on the title.

  1. She wants a ride on my truck
  2. My car is super fast
  3. Her car is yellow

If this is possible, query should return only posts 2 and 3.

Any help is greatly appreciated.

2
  • 1
    If you have some MySQL knowledge, you'd achieve this. your search returns 3 posts because the first one contains the word 'car' in the content. See this blog post sam.elegance-style.com/2015/08/08/wordpress/… replace WHERE post_content LIKE '%$query%' with WHERE post_title LIKE '%$query%'
    – Ismail
    Commented Oct 12, 2015 at 22:44
  • 1
    Here are two great answers which will solve your issue: 1.) This answer by birgire. 2.) This answer by gmazzap Commented Oct 13, 2015 at 5:36

1 Answer 1

2

The answer to this question is here.

The full credit of the answer to my question goes for the author of the answer birgire.

All I had to do was slightly change is plugin "Support for post name like in WP_Query" turning it into a function like this:

add_filter( 'posts_where', 'title_like_posts_where', 10, 2 );
function title_like_posts_where(  $where, $q) {
if( $name__like = $q->get( '_name__like' ) )
{
    global $wpdb;
    $where .= $wpdb->prepare(
        " AND {$wpdb->posts}.post_name LIKE %s ",
        str_replace( 
            array( '**', '*' ), 
            array( '*',  '%' ),  
            mb_strtolower( $wpdb->esc_like( $name__like ) ) 
        )
    );
}
return $where;
}

A special thanks to Pieter Goosen for pointing my out to the solution.

3
  • You should post your code as you hve said you have changed it, otherwise your question is just a duplicate ;-) Commented Oct 13, 2015 at 17:11
  • 1
    @PieterGoosen Thanks, again! By the way, do you know how can I multiple words in the title instead of just one? Example: How can I query '_name__like' => 'Her car*'
    – bpy
    Commented Oct 13, 2015 at 17:19
  • Unfortunately not, my SQL is really bad. Would be great if @birgire can see the post and comment ;-) Commented Oct 13, 2015 at 17:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.