每个类别只能获得一个定制帖子

时间:2019-09-26 作者:Arun

我已经创建了自定义帖子(书)。其中我有五个纺织分类:CatA、CatB、CatC、CatD、CatE&;我只想显示3个帖子,我希望这些帖子来自CatA、CatC、CatD。(这些类别各一篇帖子。)

<?php

        $args = array(
            \'post_type\' => \'book\',
            \'posts_per_page\' => \'3\',
            $terms = get_terms( array(
            \'taxonomy\' => \'categories\',
            \'field\' => \'name\',
            \'terms\' => array(\'CatA\', \'CatB\', \'CatC\')
            ))
        );

        $query = new WP_Query( $args );

        if ( $query->have_posts() ) { ?>
            <?php while ( $query->have_posts() ) { $query->the_post(); ?>
                <div style="background-image:url(\'<?php echo get_the_post_thumbnail_url(\'\'`enter code here`);?>\')">
                </div>

                <?php the_title();?>

            <?php } // end while ?>

        <?php } wp_reset_postdata(); ?>

2 个回复
SO网友:Ted Stresen-Reuter

您可能需要使用taxonomy query 而不是terms 字段(我看不到terms 作为上的有效参数WordPress\'s WP_Query documentation page). 这stackexchange question and answer 应该为您提供必要的代码来执行您正在尝试的操作。

但是,如果类别不是自定义分类法(或者实际上只是类别),那么您可以use one of the approaches here.

SO网友:Chetan Vaghela

请尝试以下代码,以从每个术语中仅获取一个自定义帖子。用中的术语ID替换术语ID$array_term = array(16,21);

    # pass your term IDS
    $array_term = array(16,21); 
    $terms_array = array( 
      \'taxonomy\' => \'categories\',// you can change it according to your taxonomy
      \'include\' => $array_term,
      \'parent\'   => 0 // If parent => 0 is passed, only top-level terms will be returned
    );

    $categories_terms = get_terms($terms_array); 
    foreach($categories_terms as $categorie_term): ?>
        <h4><?php echo $categorie_term->name; ?></h4>
        <?php 
        $post_args = array(
              \'posts_per_page\' => 1,
              \'post_type\' => \'book\', // you can change it according to your custom post type
              \'tax_query\' => array(
                  array(
                      \'taxonomy\' => \'categories\', // you can change it according to your taxonomy
                      \'field\' => \'term_id\', // this can be \'term_id\', \'slug\' & \'name\'
                      \'terms\' => $categorie_term->term_id,
                  )
              )
        );
        $query = new WP_Query($post_args); 
            if ( $query->have_posts() ) 
            {
                while ( $query->have_posts() ) 
                {
                    $query->the_post(); 
                    ?>
                    <li>
                        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                     </li>
                    <?php
                }
           }
         wp_reset_postdata(); 
    endforeach; // End Term foreach; 
让我知道这对你是否有效

相关推荐