sinanisler logo

Add Category & Tags to Search, WordPress

Normally WordPress search only searches the titles and contents of posts or post types

this code adds tags and categories to the results. if the search matches with the tags or cats results will be included in the search.

function enhance_search_query($query) {
    // Only target the main query on the front-end search page
    if ($query->is_main_query() && !is_admin() && $query->is_search) {
        // Ensure we are only modifying the 'publish' status posts
        $query->set('post_status', 'publish');
        
        add_filter('posts_search', 'custom_posts_search', 10, 2);
    }
}

add_action('pre_get_posts', 'enhance_search_query');

function custom_posts_search($search, $wp_query) {
    global $wpdb;
    
    // Check if it's a search query
    if (!empty($search) && !empty($wp_query->query_vars['s'])) {
        $terms = $wp_query->query_vars['s'];

        // Constructing search conditions
        $search_terms = explode(' ', $terms);
        $search_conditions = [];
        
        foreach ($search_terms as $term) {
            $like = '%' . $wpdb->esc_like($term) . '%';
            $search_conditions[] = $wpdb->prepare("($wpdb->posts.post_title LIKE %s)", $like);
            $search_conditions[] = $wpdb->prepare("($wpdb->posts.post_content LIKE %s)", $like);
            // For tag and category names, this could be more complex and might need a direct SQL approach or a different hook to integrate smoothly
        }
        
        // Remove the default search condition
        $search = "AND (" . implode(' OR ', $search_conditions) . ")";
    }
    
    return $search;
}

This snippet was created for one of the client project of geopard.digital.

Leave the first comment