列出具有自定义分类类别的自定义帖子类型

时间:2020-06-04 18:25:36

标签: php wordpress

我有一个名为products的自定义帖子类型和一个名为product-category的自定义分类法。 现在,我需要列出该产品发布类型中所有分配了产品类别的发布。我以为这样的事情可能行得通,但是没有运气。有人能指出我正确的方向吗?非常感谢您的帮助!

enter image description here

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

1 个答案:

答案 0 :(得分:1)

您可能需要将relation添加到参数中。

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

还要检查:

  • 帖子类型的拼写是否正确(即您确定它是products而不是product吗?)
  • 在第一个查询中,您有product_category,但是在第二个查询中,您有product-category。应该是连字符还是下划线?
  • $category返回的值是否有效?