首页 > 解决方案 > 首先按自定义分类对cpt进行排序,然后是帖子的其余部分

问题描述

我正在尝试显示自定义帖子类型空缺中的 3 个最新帖子。但是是否有任何帖子的自定义分类“选项”值等于“特色”,那么它们应该首先显示。

因此,如果 2x 帖子被标记为“精选”,那么它们将首先显示,然后仅显示最近的帖子。下面的代码只会显示标记为“特色”的帖子,但如果只有 1 或 2 个帖子标记为特色,我将不会看到 3 个帖子。

任何建议将不胜感激。谢谢你。

`$loop_args = array (
'post_type' => 'vacancies',
'posts_per_page' => 3,
'tax_query' => array(
   array(
  'taxonomy' => 'option',
  'field' => 'slug',
  'terms' => 'featured'
 )
 )
);
$custom_loop = new WP_Query( $loop_args );
while ( $custom_loop->have_posts() ) : $custom_loop->the_post();

$intro = get_field( 'vacancy_introduction' );
$area = get_field( 'vacancy_area' );

<?php the_title( '<h2>', '</h2>' );?>
<h3>
  <?php if( $area ): ?>
  <?php echo $area; ?>
  <?php endif; ?>
</h3>
<div>
  <?php if( $intro ): ?>
  <?php echo $intro; ?>
<?php endif; ?>
</div>

<a class="morex" href="<?php echo get_permalink(); ?>"><button><?php _e('Read More', 'tsum'); ?></button></a>

<?php endwhile; wp_reset_query(); ?>`

标签: wordpresssortingfiltercustom-post-typecustom-taxonomy

解决方案


您可以在初始循环之后简单地添加。(在你结束之后)

但是删除您的wp_reset_query,以便您仍然可以访问计数。

<?php
$count = $custom_loop->found_posts;
if ($count < 3){
    $show = $count - 3;
    $second_loop = array (
        'post_type' => 'vacancies',
        'posts_per_page' => $show,
        'tax_query' => array(
           array(
              'taxonomy'    => 'option',
              'field'       => 'slug',
              'terms'       => 'featured',
              'operator'    => 'NOT IN',
                )
            )
        );

    $custom2 = new WP_Query($second_loop);

    while ( $custom2->have_posts() ) : $custom2->the_post();

    $intro = get_field( 'vacancy_introduction' );
    $area = get_field( 'vacancy_area' ); ?>

    <?php the_title( '<h2>', '</h2>' );?>
    <h3>
      <?php if( $area ): ?>
      <?php echo $area; ?>
      <?php endif; ?>
    </h3>
    <div>
      <?php if( $intro ): ?>
      <?php echo $intro; ?>
    <?php endif; ?>
    </div>

    <a class="morex" href="<?php echo get_permalink(); ?>"><button><?php _e('Read More', 'tsum'); ?></button></a>

    <?php endwhile; wp_reset_query();

}

推荐阅读