类别循环显示所有 post 标题 (WordPress)
Category loop is showing all post titles (WordPress)
我似乎无法让它正常工作。
此代码应该遍历自定义分类法中的所有类别,并在每个类别标题下显示 post 个标题:
$args = array(
'post_type' => 'news',
'taxonomy' => 'news_category',
'orderby' => 'name'
);
$categories = get_categories( $args );
foreach ( $categories as $category ) {
$posts = get_posts($args);
echo '<h2>' . $category->name . '</h2>'; ?>
<ul>
<?php foreach($posts as $post) { ?>
<li>
<?php the_title(); ?>
</li>
<?php
} ?>
</ul>
<?php
}
预期的结果是这样的...
类别 1
- 一个post标题
- 另一个post标题
类别 2
- 还有一个post标题
类别 3
- 嘿,看,另一个 post 标题
- 还有一个 post 标题只是为了好玩
...但我得到的是:
类别 1
- 一个post标题
- 另一个post标题
- 还有一个post标题
- 嘿,看,另一个 post 标题
- 还有一个 post 标题只是为了好玩
类别 2
- 一个post标题
- 另一个post标题
- 还有一个post标题
- 嘿,看,另一个 post 标题
- 还有一个 post 标题只是为了好玩
类别 3
- 一个post标题
- 另一个post标题
- 还有一个post标题
- 嘿,看,另一个 post 标题
- 还有一个 post 标题只是为了好玩
我该如何解决这个问题?
我认为这是因为当你使用 get_posts 时你没有指定任何要搜索的分类术语,因为你再次使用你的 $args var 并且它只包含用于获取你的类别的一般参数.
为了使它成为你想要的方式,你应该在调用 get_posts 时用这样的东西替换 $args:
$postArgs = array(
'post_type' => 'news',
'tax_query' => array(
array(
'taxonomy' => 'news_category',
'field' => 'slug',
'terms' => $category->slug,
),
),
);
$posts = get_posts($postArgs);
有关您可以做什么的确切文档可在此处找到 https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters。
WP_Query 与 get_posts
的工作原理相同
我似乎无法让它正常工作。
此代码应该遍历自定义分类法中的所有类别,并在每个类别标题下显示 post 个标题:
$args = array(
'post_type' => 'news',
'taxonomy' => 'news_category',
'orderby' => 'name'
);
$categories = get_categories( $args );
foreach ( $categories as $category ) {
$posts = get_posts($args);
echo '<h2>' . $category->name . '</h2>'; ?>
<ul>
<?php foreach($posts as $post) { ?>
<li>
<?php the_title(); ?>
</li>
<?php
} ?>
</ul>
<?php
}
预期的结果是这样的...
类别 1
- 一个post标题
- 另一个post标题
类别 2
- 还有一个post标题
类别 3
- 嘿,看,另一个 post 标题
- 还有一个 post 标题只是为了好玩
...但我得到的是:
类别 1
- 一个post标题
- 另一个post标题
- 还有一个post标题
- 嘿,看,另一个 post 标题
- 还有一个 post 标题只是为了好玩
类别 2
- 一个post标题
- 另一个post标题
- 还有一个post标题
- 嘿,看,另一个 post 标题
- 还有一个 post 标题只是为了好玩
类别 3
- 一个post标题
- 另一个post标题
- 还有一个post标题
- 嘿,看,另一个 post 标题
- 还有一个 post 标题只是为了好玩
我该如何解决这个问题?
我认为这是因为当你使用 get_posts 时你没有指定任何要搜索的分类术语,因为你再次使用你的 $args var 并且它只包含用于获取你的类别的一般参数.
为了使它成为你想要的方式,你应该在调用 get_posts 时用这样的东西替换 $args:
$postArgs = array(
'post_type' => 'news',
'tax_query' => array(
array(
'taxonomy' => 'news_category',
'field' => 'slug',
'terms' => $category->slug,
),
),
);
$posts = get_posts($postArgs);
有关您可以做什么的确切文档可在此处找到 https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters。
WP_Query 与 get_posts
的工作原理相同