如何在wp post循环中打印术语名称?

时间:2019-11-26 08:48:44

标签: wordpress

我在自定义帖子类型中有3种不同的分类法。我想打印所有带有术语名称的帖子。

例如:

分类1 => taxonomy = banks&post_type =信用卡

分类2 => taxonomy = joiningfees&post_type =信用卡

分类3 => taxonomy = cardtype&post_type =信用卡

所以我想打印所有带有术语名称的自定义帖子 我可以通过输入单一分类法来打印数据,但是如何使用所有分类法术语来打印数据

查询

<?php
    $custom_terms = get_terms('banks');

    foreach($custom_terms as $custom_term) {
       wp_reset_query();
       $args = array('post_type' => 'creditcards',
           'tax_query' => array(
           array(
                 'taxonomy' => 'banks',
                 'field' => 'slug',
                 'terms' => $custom_term->slug,
                ),
           ),
       );

       $loop = new WP_Query($args);
       if($loop->have_posts()) {

           while($loop->have_posts()) : $loop->the_post();
?>
               <div>
                  <?php echo $custom_term->name;?><br><?php echo the_title();?> 
               </div>
<?php 
           endwhile;
       }
    }
?>

在循环后我想要的最终结果


    taxonomy1 term,taxonomy2 term,taxonomy3 term
    the title

    taxonomy1 term,taxonomy2 term,taxonomy3 term
    the title

    taxonomy1 term,taxonomy2 term,taxonomy3 term
    the title

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以使用get_terms中的数组获得多个分类法术语。用以下代码替换您的代码:

$args = array('post_type' => 'creditcards',
    'posts_per_page' => -1
);

$loop = new WP_Query($args);

if ($loop->have_posts()) {

    while ($loop->have_posts()) : $loop->the_post();
        $custom_terms = wp_get_post_terms(get_the_ID(), array(
            'banks',
            'joiningfees',
            'cardtype'), array("fields" => "all"));

        $custom_term = wp_list_pluck($test, 'name'); //To get term name from term taxonomy array

        echo join(', ', $custom_term); //This will print all term name and remove ',' from last term name
        ?>
        <div>
            <strong>
                <?php echo the_title(); ?>
            </strong>
        </div>
        <?php
    endwhile;
}