从搜索循环中排除WooCommerce产品



我正在尝试创建一个自定义搜索结果页面,其中WooCommerce产品结果单独显示为博客/一般帖子。

我的目的是将它们显示为具有不同样式的单独块。

[Block 1] - Woocommerce results
[Block 2] - Blog / Post results

我设法在一个循环中显示产品,但我正在努力将产品排除在邮政循环中。

我尝试创建一个自定义循环,但是这只是在这些术语中显示所有帖子,而不是在搜索中返回的帖子。

我通常使用的循环是:

<?php $loop = new WP_Query( array( 'post_type' => 'post' ?>
    <p>Something here</p>
<?php endwhile; wp_reset_query(); ?>

但是,我相信这只是不兼容,适合我的需求。

如果有更好的解决方案来分开这些,我绝对希望听到更多。

您存在的问题是您有一个主要查询,实际上您想在其中进行两个查询。您当然可以修改主要查询以包含两个帖子类型,但是您最终会得到两个随机数的帖子类型。

如果您将主查询修改为仅返回其中一列,则最终会遇到一种情况,可以运行另一个查询以获取其余帖子。我认为如果需要的话,您应该可以使用posts_joinposts_where过滤器,但是我不确定posts_search。您可以使用WP_Queryget_posts最终进行您需要的两个查询。

<?php
  // Since we are searching, we probably should get the search keyword
  $search = get_query_var('s');
  // Since we want to be able to navigate, we probably should figure out on which page we are
  $paged = get_query_var('paged');
  // Anything else we want to do in search queries we should be able to do in 
  // a posts_join or posts_where filter by checking if is_search() is true
  // With that out of the way, we can construct our queries
  $query_posts_page = new WP_Query([
    's' => $search,
    'paged' => $paged,
    'post_type' => ['post', 'page']
  ]);
  $query_woocommerce = new WP_Query([
    's' => $search,
    'paged' => $paged,
    'post_type' => 'product'
  ]);
?>
<div class="col">
  <?php
    if ( $query_posts_page->have_posts() ) {
      while ( $the_query->have_posts() ) {
        $query_posts_page->the_post();
        echo get_the_title();
      }
      /* Restore original Post Data */
      wp_reset_postdata();
    } else {
      echo 'Nope, no more data';
    }
  ?>
</div>
<div class="col">
  <?php
    if ( $query_woocommerce->have_posts() ) {
      while ( $query_woocommerce->have_posts() ) {
        $query_posts_page->the_post();
        echo get_the_title();
      }
      /* Restore original Post Data */
      wp_reset_postdata();
    } else {
      echo 'Nope, no more data';
    }
  ?>
</div>

但是还有另一个问题。考虑到我们正在运行两个自定义查询,而不是主要查询,我们无法自动生成分页。此外,我们不太可能拥有相等数量的普通页面/帖子和产品。

我们可以使用max_num_pages弄清楚每个循环的最大页数是多少。您可以自己生成一些东西。

<?php
  $maximum_page = max($query_posts_page->max_num_pages, $query_woocommerce->max_num_pages);
  for( $i = 1; $i < $maximum_page; $i++) {
    echo "{$i} ";
  }

最新更新