Php 类别循环显示所有帖子标题(WordPress)

Php 类别循环显示所有帖子标题(WordPress),php,wordpress,foreach,categories,Php,Wordpress,Foreach,Categories,我似乎无法让它正常工作 此代码应循环遍历自定义分类法中的所有类别,并在每个类别标题下显示文章标题: $args = array( 'post_type' => 'news', 'taxonomy' => 'news_category', 'orderby' => 'name' ); $categories = get_categories( $args ); foreach ( $categories as $category ) { $p

我似乎无法让它正常工作

此代码应循环遍历自定义分类法中的所有类别,并在每个类别标题下显示文章标题:

$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
}
$args=array(
“post_type”=>“news”,
“分类法”=>“新闻分类”,
'orderby'=>'name'
);
$categories=get_categories($args);
foreach($categories作为$category){
$posts=get_posts($args);
回显“.$category->name.”;?>

我认为这是因为当您使用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);
这里提供了您可以执行的操作的确切文档


WP_Query的工作原理与get_posts相同

您得到的结果是什么?每次调用
$posts=get_posts($args);
都将返回所有帖子。您必须从当前类别中获取帖子。