phpwordpresscustom-post-typetaxonomy

Search in custom post type and taxonomy with specific tag


I have two custom post type: product and faq. The product post type has a taxonomy product_tag. So now, I want to search for text 'food' in both blog and faq and those products having tag as 'food'.

This is the arguments for the query:

$args = array(
    'tax_query' => array(
        array(
            'taxonomy' => 'product_tag',
            'field' => 'slug',
            'terms' => 'food'
        )
    ),
    'post_type' => array('post', 'faq', 'product'),
    'posts_per_page' => 6,
    's' => 'food',
    'paged' => $paged
);

But I am not getting any result. If I remove the tax_query array from the code, I get the results but not all products having food as tags are displayed. It just search for the text in them.

So, what should be the modification needed so that I get relevant posts here?


Solution

  • For anyone having interest, this is how I solved it:

    <?php
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    
    $args1 = array(
        'post_type' => array('post', 'faq'),
        'posts_per_page' => 6,
        's' => $problem,
        'paged' => $paged
    );
    
    $args2 = array(
        'tax_query' => array(
            array(
                'taxonomy' => 'product_tag',
                'field' => 'slug',
                'terms' => $problem
            )
        ),
        'post_type' => 'product',
        'posts_per_page' => 6,
        'paged' => $paged
    );
    
    $articleposts = get_posts( $args1 );
    $productposts = get_posts( $args2 );
    
    $mergedposts = array_merge( $articleposts, $productposts );
    
    foreach( $mergedposts as $singlepost ) : setup_postdata( $singlepost );
    ?>
    <h2><a href="<?php echo get_permalink( $singlepost->ID ); ?>"><?php echo $singlepost->post_title; ?></a></h2>
    <?php endforeach; ?>