loop - Query posts by specific word on title

admin2025-06-02  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.

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.

Share Improve this question edited Oct 12, 2015 at 22:40 bpy asked Oct 12, 2015 at 22:33 bpybpy 2995 silver badges20 bronze badges 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/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 – Pieter Goosen Commented Oct 13, 2015 at 5:36
Add a comment  | 

1 Answer 1

Reset to default 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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748840950a314167.html

最新回复(0)