首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WordPress -在archive.php中可以有两个查询吗?

WordPress -在archive.php中可以有两个查询吗?
EN

Stack Overflow用户
提问于 2020-04-05 00:52:46
回答 1查看 305关注 0票数 0

出于某种原因,我需要在归档页面中发布两次查询文章,它们需要不同的页面限制。

例如,第一个查询需要显示10个具有一些自定义字段的帖子。第二个查询需要显示20个具有不同自定义字段的帖子。

它看起来不错,但是当我在第二个查询中添加'showposts=10‘时,它看起来显示的是帖子,但不属于当前类别。

代码语言:javascript
复制
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
    <?php the_field('custom-fields-1'); ?>
<?php endwhile; ?>
<?php else : ?>
    <h3>Not Found</h3>
<?php endif; ?>
<?php wp_reset_query();?>

<?php query_posts('showposts=10'); if (have_posts()) : while (have_posts()) : the_post(); ?>
    <?php the_field('custom-fields-2'); ?>
<?php endwhile; ?>
<?php else : ?>
    <h3>Not Found</h3>
<?php endif; ?>
<?php wp_reset_query();?>
EN

回答 1

Stack Overflow用户

发布于 2020-04-05 11:19:21

因此,这里需要的是get_queried_object 函数获取查询对象来提取当前的类别id,然后使用WP_Query类而不是get_posts来执行循环。从下面的内容来看,您应该能够修改它以满足您的需要。

代码语言:javascript
复制
  $catObject = get_queried_object();
  $category = $catObject->term_id;


  // WP_Query arguments for first loop
  $args = array(
    'posts_per_page' => '10',
    'tax_query' => array(
      array(
        'taxonomy' => 'category',
        'terms' => $category,
      ),
    ),
    'meta_query' => array(
      'relation' => 'AND',
      array(
        'key' => 'custom_field_1',
        'compare' => 'EXISTS',
      ),
    ),
  );

  // The Query
  $query = new WP_Query( $args );

  // The Loop
  if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
      $query->the_post();
      // Do your stuff with the first loop
    }
  } else {
    // no posts found
  }
  // Restore original Post Data
  wp_reset_postdata();

  // WP_Query arguments for second loop
  $args2 = array(
    'posts_per_page' => '10',
    'tax_query' => array(
      array(
        'taxonomy' => 'category',
        'terms' => $category,
      ),
    ),
    'meta_query' => array(
      'relation' => 'AND',
      array(
        'key' => 'custom_field_2',
        'compare' => 'EXISTS',
      ),
    ),
  );

  // The Query
  $query2 = new WP_Query( $args2 );

  // The Loop
  if ( $query2->have_posts() ) {
    while ( $query2->have_posts() ) {
      $query2->the_post();
      // Do your stuff with the second loop
    }
  } else {
    // no posts found
  }
  // Restore original Post Data
  wp_reset_postdata();
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61036732

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档