简体   繁体   中英

List custom post types with custom taxonomy category assigned to them

I have a custom post type called products and custom taxonomy called product-category . Now I need to list all the posts from this 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!

在此处输入图像描述

<?php $category = get_search_query();

$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(); ?>

You might need to add the relation to your args.

$args = array(
    'post_type'      => 'products',
    'posts_per_page' => -1,
    'tax_query'      => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'product_category',
            'terms'    => $category,
            'field'    => 'slug',
        ),
    ),
);

Also, check:

  • Is the post type spelled correctly (ie Are you sure it's products and not product ?)
  • In your first query you have product_category but in your second query you have product-category . Should it be a hyphen or an underscore?
  • Is the value returned by $category valid?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM