Darkering
Darkering

Reputation: 35

WP_Query filter custom taxonomy OR keyword search in custom post_type

I wonder if Is it posible filter by post title OR custom taxonomy.

For example: I search 'human', I want to show the posts that contain the word 'human' in the post title and the category 'human'.

-No exclude posts if 'human' category not exists and there are posts with the title 'human'

-No exclude posts if 'human' category exists and there are posts with the title 'human'(retrieve all posts that contains the word 'human' and all post with the category 'human')

Upvotes: 3

Views: 3226

Answers (2)

coding-dude.com
coding-dude.com

Reputation: 808

Not sure if you found a solution for this or not, but I think that Gufran's answer is not exactly the one that solves the problem.

I also needed to do a search within title, content, excerpt OR category names and ran into a problem because the query excludes hits that are outside the category. My solution was to do 2 queries and combine the results.

//search within title of category
$args1 = array(  
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => 500, 
    'orderby' => 'title', 
    'order' => 'ASC', 
    'tax_query' => array(
        array(
            'taxonomy' => 'category',
            'field'    => 'title',
            'terms'    => 'human',
        )
    )
);

//search within title/excerpt/content
$args2 = array(  
    's' => 'human',
    'post_type' => 'businesses',
    'post_status' => 'publish',
    'posts_per_page' => 500, 
    'orderby' => 'title', 
    'order' => 'ASC'
);

$query1 = new WP_Query($args1);
$query2 = new WP_Query($args2);
$loop = new WP_Query();
$loop->posts = array_merge( $query1->posts, $query2->posts );

//populate post_count count for the loop to work correctly
$loop->post_count = $query1->post_count + $query2->post_count;

Upvotes: 1

Gufran Hasan
Gufran Hasan

Reputation: 9373

I think should try this filter posts_where

Method 1:

in functions.php file

  <?php
    add_filter( 'posts_where', 'title_like_posts_where', 10, 2 );
    function title_like_posts_where( $where, &$wp_query ) {
        global $wpdb;
        if ( $post_title_like = $wp_query->get( 'post_title_like' ) ) {
            $where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( $wpdb->esc_like( $post_title_like ) ) . '%\'';
        }
        return $where;
    }
    ?>

Then pass args like:

$args = array(
    'post_title_like' => $str
);
$res = new WP_Query($args);

Method 2:

    $mypostids = $wpdb->get_col("select ID from $wpdb->posts where post_title LIKE '".$str."%' ");

    $args = array(
        'post__in'=> $mypostids,
        'post_type'=>'post',
        'orderby'=>'title',
        'order'=>'asc'
    );

    $res = new WP_Query($args);

    while( $res->have_posts() ) : $res->the_post();    
        // put your logic here
    endwhile;

Upvotes: 5

Related Questions