• Resolved hassanjunaid

    (@hassanjunaid)


    I am developing a WordPress theme for mobile review website on a localhost and want to modify the search functionality by adding custom post type and custom taxonomy to the search results. The code is working fine for the custom post types, but I am facing issues with the custom taxonomy as it returns no results when search is made using custom taxonomy.

    I have manually registered the custom taxonomy with the name of “mobile-brand” which has the different brands like Apple, Samsung etc. as the sub-categories.

    Following is my code written in functions.php file for implementation of this task. But, it is not giving me the desired output.

    Thanks in advance for the help.

    function custom_search_query( $query ) {

    if ( $query->is_search && !is_admin() ) {
    // Include custom post types in search
    $query->set( 'post_type', array( 'post', 'page', 'mobile' ) );
    // Get the search term
    $search_term = get_search_query();
    if ( ! empty( $search_term ) ) {
    // Search in the custom taxonomy (mobile-brand)
    $tax_query = array(
    array(
    'taxonomy' => 'mobile-brand', // Custom taxonomy
    'field' => 'name',
    'terms' => $search_term,
    ),
    );

    // Set the taxonomy query in the main query
    $query->set( 'tax_query', $tax_query );
    }
    }
    }
    add_action( 'pre_get_posts', 'custom_search_query' );
Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator t-p

    (@t-p)

    Moderator bcworkz

    (@bcworkz)

    The way you’ve modified the query is requiring results to match the search term both in title or content AND taxonomy term name. You actually need OR logic to get what you want. Sadly, there’s no way within WP_Query query vars to invoke OR search logic for taxonomy terms. To achieve OR logic you would use the “posts_request” filter to modify the actual SQL query. Search for the correct AND and replace it with OR.

    The accepted SE answer that t-p linked to is an alternative solution of doing two separate queries. One for posts and one for terms. Depending on whether you’re OK with separate results or you need them mixed together, the SE solution or my solution would be more appropriate.

    Thread Starter hassanjunaid

    (@hassanjunaid)

    Thank you for your response, @t-p , @bcworkz . This helped a lot.

Viewing 3 replies - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.