我想获取所有类别和属于该类别的帖子,以获取所有类别,我使用以下代码
$cat_args = array(
'taxonomy' => 'article-category',
'orderby' => 'menu_order',
'order' => 'ASC',
'hierarchical' => true,
'parent' => 0,
'hide_empty' => true,
'child_of' => 0
);
$get_categories = get_categories( $cat_args );
要获取所有类型文章的帖子,我正在使用此代码
$query = new WP_Query(array(
'post_type' => 'article',
'post_status' => 'publish',
'posts_per_page' => -1,
));
while ($query->have_posts()) {
$query->the_post();
$post_id = get_the_ID();
}
这给了我所有类别的列表以及单独循环中所有类型文章的列表,但是我想要的是这一行中的内容
Category 1
- Post 1 Title
- Post 2 Title
- Post 3 Title
Category 2
- Post 4 Title
- Post 5 Title
- Post 6 Title
- Post 7 Title
...
...
我基本上是在尝试获取属于此类别的所有类别和所有类型文章的帖子,我尝试了许多不同的方法,但似乎没有任何结果,如何去解决它?
感谢。
答案 0 :(得分:2)
请尝试以下答案,因为您需要在循环中进一步应用单词印刷代码以获取适当格式的数据。根据您的具体设计,您可以在成功显示数据后通过删除和
标记来设置UL / LI。
$cat_args = array(
'taxonomy' => 'article-category',
'orderby' => 'menu_order',
'order' => 'ASC',
'hierarchical' => true,
'parent' => 0,
'hide_empty' => true,
'child_of' => 0
);
$get_categories = get_categories( $cat_args );
foreach($get_categories as $get_category){
$ids[] = $get_category->term_id;
}
$finalCatPostData = '';
foreach($ids as $id){
$finalCatPostData .= '<h2>'.get_cat_name( $id ).'</h2>';
$args = array(
'category' => $id,
'orderby' => 'date',
'post_type' => 'article',
'post_status' => 'publish',
'suppress_filters' => true,
'posts_per_page' => -1,
);
$posts_array = get_posts( $args );
foreach($posts_array as $post){
$finalCatPostData .= '<p>'.$post->post_title.'</p>';
}
}
echo $finalCatPostData;
<强>输出:强>
cat 1
post 1 of cat 1
post 2 of cat 1
cat 2
post 1 of cat 2
post 2 of cat 2
cat 3
post 1 of cat 3
post 2 of cat 3
答案 1 :(得分:1)
不完全是解决方案,但您可以遵循以下逻辑
1)获取类别
$cat_args = array(
'taxonomy' => 'article-category',
'orderby' => 'menu_order',
'order' => 'ASC',
'hierarchical' => true,
'parent' => 0,
'hide_empty' => true,
'child_of' => 0
);
$get_categories = get_categories( $cat_args );
2)循环浏览每个类别并获取帖子,将它们添加到最终数组
$mFinalArray = []; // init empty array
foreach($get_categories as $category){
$query = new WP_Query(array(
'post_type' => 'article',
'post_status' => 'publish',
'posts_per_page' => -1,
'category_name' => $category, // fetch all posts that are in current $category
));
while ($query->have_posts()) {
$query->the_post();
$mFinalArray[$category][] = get_post(get_the_ID()); // add post under current category
}
// reset loop here
}
输出就是这样:
Array(
[a_category_name_example1] => array(many_posts_here_of_this_category),
[a_category_name_example2] => array(many_posts_here_of_this_category),
)
考虑使用上面的代码,因为它可能不完全正确。