List custom post types with custom taxonomy category assigned to them

Question

I have a custom post type called products and custom taxonomy called product-category.
Now I need to list all the posts from product post type which have product-category assigned to them. I thought something like this could work, but no luck. Could anyone point me in the right direction, please?! Really appreciate your help!


$args = array(
    'taxonomy'      => 'product_category',
    'post_type'     => 'products',
    'category_name' => $category
);
$query = new WP_Query( $args );

// OR

$args = array(
    'post_type'     => 'products',
    'tax_query' => array(
        array(
            'taxonomy' => 'product-category',
            'field' => 'slug',
            'terms' => $category
        )
    )
);
$query = new WP_Query( $args ); ?>


<?php if ( $query->have_posts() ): ?>
    <div class="products">
        <ul>
            <?php while ( $query->have_posts() ): $query->the_post(); ?>

                <li><?php get_template_part( 'template-parts/content', 'search' ); ?></li>

            <?php endwhile; ?>
        </ul>
    </div>
<?php else: ?>
    <?php get_template_part( 'template-parts/content', 'none' ); ?>
<?php endif; ?>

<?php wp_reset_postdata(); ?>```


0
, Kai 4 years 2020-06-04T15:11:43-05:00 0 Answers 96 views 0

Leave an answer

Browse
Browse