Himanshu Bhuyan
Himanshu Bhuyan

Reputation: 306

WordPress - Search posts by Taxonomy

My custom wp search query in

$args = array(
        'post_type' => 'post',
        'taxonomy'  => 'location',
        'field' => 'name',
        'posts_per_page' => 10,
        'term' => $keyword,
    );
$wp_query = new WP_Query($args);

I have 2 post which location is London and oxford,london .Now when i search london then it show only 1 post**(1st one)** .Also when i search oxford then it show no result found.

When i search oxford london then its working fine.

Upvotes: 0

Views: 2309

Answers (1)

Harsh
Harsh

Reputation: 496

Befor WP_Query Run write this code

function advance_search_where($where){
    global $wpdb;
    if (is_search())
        $where .= "OR (t.name LIKE '%".get_search_query()."%' AND {$wpdb->posts}.post_status = 'publish')";
    return $where;
}

function advance_search_join($join){
    global $wpdb;
    if (is_search())
        $join .= "LEFT JOIN {$wpdb->term_relationships} tr ON {$wpdb->posts}.ID = tr.object_id INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id=tr.term_taxonomy_id INNER JOIN {$wpdb->terms} t ON t.term_id = tt.term_id";
    return $join;
}

function advance_search_groupby($groupby){
    global $wpdb;

    // we need to group on post ID
    $groupby_id = "{$wpdb->posts}.ID";
    if(!is_search() || strpos($groupby, $groupby_id) !== false) return $groupby;

    // groupby was empty, use ours
    if(!strlen(trim($groupby))) return $groupby_id;

    // wasn't empty, append ours
    return $groupby.", ".$groupby_id;
}

add_filter('posts_where','advance_search_where');
add_filter('posts_join', 'advance_search_join');
add_filter('posts_groupby', 'advance_search_groupby');

Now Run Your WP_Query Like this

$args = array(
        'post_type' => 'post',
        'posts_per_page' => 10,
        's' => $keyword,
    );
$wp_query = new WP_Query($args);

After all your result and that you want you have to just remove the above filter coz if you not remove that then it will apply in other wp_query of that page.

remove_filter('posts_where','advance_search_where');
remove_filter('posts_join', 'advance_search_join');
remove_filter('posts_groupby', 'advance_search_groupby');

Upvotes: 3

Related Questions