列出具有特定分类的所有定制帖子,无论这些术语是什么

时间:2018-10-29 作者:Pierre

我想获得属于特定分类法的所有自定义帖子的列表。

我尝试了很多东西,包括这段代码,但我得到了“成员”cpt中所有帖子的列表,而不仅仅是与“生产者”分类法相关的帖子。我怎样才能让它工作?

<?php
$args = array(
        \'post_type\' => \'members\',
         \'posts_per_page\' => -1,
         \'tax_query\' => array(
        \'taxonomy\' => \'producers\'
),
);
    $the_query = new WP_Query($args);
    while ( $the_query->have_posts() ) : $the_query->the_post();
        ?>
            <li class="producers" id="post-<?php the_ID(); ?>">
                    <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
            </li>
            <?php
    endwhile;
 ?>
编辑2018-10-31

我最终通过本机WP函数和一个自定义查询实现了这一点。我还需要分页功能,所以我这样构建它。

    $termArray = [];
    $theTerms = get_terms(\'producers\');
    foreach ($theTerms as $singleTerm) {
        $theSlug = $singleTerm->slug;
        array_push($termArray,$theSlug);
    }
    $paged = ( get_query_var( \'paged\' ) ) ? get_query_var( \'paged\' ) : 1;
    $loop = new WP_Query( array( \'post_type\' => \'members\', \'orderby\' => \'rand\', \'posts_per_page\' => 5, \'paged\' => $paged, \'tax_query\' => array(
        array(
            \'taxonomy\' => \'producers\',
            \'terms\'    => $termArray,
        )
    )));
    if ( $loop->have_posts() ) :
        while ( $loop->have_posts() ) : $loop->the_post();
        $terms = get_the_terms( $post->ID, \'producers\');
        if ($terms) {
            /// Here is the code for posts display
        }
    endwhile;
    endif;
    wp_reset_postdata();


// Pagination
    $big = 99999;
    echo paginate_links( array(
        \'base\' => str_replace( $big, \'%#%\', esc_url( get_pagenum_link( $big ) ) ),
        \'format\' => \'?paged=%#%\',
        \'current\' => max( 1, get_query_var(\'paged\') ),
        \'total\' => $loop->max_num_pages
    ));

2 个回复
SO网友:Peter HvD

正确的使用方法tax_query 参数的数组包含一个数组,如下所示:

\'tax_query\' => array(
    array (
        \'taxonomy\' => \'producers\'
    )
),
请参见Codex entry 了解更多信息。

SO网友:Adarsh

Try this

<?php
$custom_args = array(\'post_type\' => \'members\',
                     \'posts_per_page\' => -1,
                     \'orderby\' => \'id\',
                     \'order\' => \'ASC\',
                     \'tax_query\' => array(array(\'taxonomy\' => \'producers\',
                                                \'field\' => \'slug\',
                                                \'terms\' => \'your term name\')));
$custom_query = get_posts($custom_args);
?>
<?php
    foreach ($custom_query as $value) 
     { ?>
       <li class="producers" id="post-<?php $value->ID ; ?>">
           <a href="<?php $value->guid ; ?>"><?php $value->post_title; ?></a>
       </li>
        <?php
     } ?>
结束

相关推荐

get the custom taxonomy name?

在我的functions.php 我有个钩子:add_action( \'woocommerce_before_single_product\', \'display_category_list\',20 ); function display_category_list() { wc_get_template( \'woocommerce/single-product/single-product-top- content.php\' );