【问题标题】:How to customize/change the loop query如何自定义/更改循环查询
【发布时间】:2021-04-24 06:27:12
【问题描述】:

我们有一个分为两列的页面。每列都有一个循环,用不同类别的帖子填充该列。

我们想要什么: A 列 - 显示类别 X 和 Y 的帖子 B 列 - 显示类别 X 的帖子(除了类别 Y 的帖子)

问题: 我们无法从 B 列中排除来自 X 类和 Y 类的帖子——我们的想法是在 B 列中仅显示 X 类的帖子

根据我们的研究,我们假设我们必须自定义 B 列中的循环,但我们不知道如何访问它。

我们在这里缺少什么?

【问题讨论】:

  • 你用的是什么主题?你是如何添加这些列的?你试过什么?您是否尝试过任何自定义查询?

标签: wordpress loops filter


【解决方案1】:

这很容易理解。当您定义一个新的自定义查询(自定义循环)时,您引用了许多反对它的参数。

在您的情况下,我们对类别参数感兴趣。

类别参数

显示与特定类别相关的帖子。

  • cat (int) – 使用类别 ID。
  • category_name (string) – 使用类别 slug。
  • category__and (array) – 使用类别 ID。
  • category__in (array) – 使用类别 ID。
  • category__not_in (array) – 使用类别 ID。

我们将使用category__incategory__not_in 参数。我们将通过使用get_category_by_slug 的类别slug 获取类别ID。

这是我们的最终结果。我已经添加了 cmets,您可以通过 looking at the CODEX 添加更多您想要的参数以查看完整列表。修改并玩得开心!

<?php
// Column A
$x = get_category_by_slug( 'category_x_slug' )->term_id; // ... get category x ID
$y = get_category_by_slug( 'category_y_slug' )->term_id; // ... get category y ID
$args = [
  'post_type' => 'post'
  'posts_per_page' => 6,
  'category__in' => [ $x, $y, ],  // ... Column A: post with category x, category y
];
$query = new WP_Query( $args ); // ... loop start
if( $query->have_posts() ):
  while( $query->have_posts() ): $query->the_post();
    // ... post template start
    the_title( '<h1>', '</h1>' );
    the_excerpt();
    // ... post template end
  endwhile;
else:
  echo "No posts yet!";
endif;  // ... loop end
wp_reset_postdata(); ?>

<?php
// Column B
$x = get_category_by_slug( 'category_x_slug' )->term_id;
$y = get_category_by_slug( 'category_y_slug' )->term_id;
$args = [
  'post_type' => 'post'
  'posts_per_page' => 6,
  'category__in' => [ $x, ],  // ... Column B: post with category x 
  'category__not_in' => [ $y, ], // ... Without post with category y
];
$query = new WP_Query( $args ); // ... loop start
if( $query->have_posts() ):
  while( $query->have_posts() ): $query->the_post();
    // ... post template start
    the_title( '<h1>', '</h1>' );
    the_excerpt();
    // ... post template end
  endwhile;
else:
  echo "No posts yet!";
endif;  // ... loop end
wp_reset_postdata(); ?>

【讨论】:

  • 非常感谢@amarinediary 的回复。我可以理解代码的作用。非常清楚(感谢详细信息和 cmets)。但据我了解,我们正在创建一个新页面。我打算编辑现有的查询(由 WordPress 生成)。我不明白在哪里插入代码来编辑 WordPress 已经创建的列。是否只能通过创建新页面来实现?我可以编辑现有的吗?我在 Wordpress 方面没有太多经验 :(
  • 任何帮助请:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-17
  • 2020-03-15
  • 1970-01-01
相关资源
最近更新 更多