我想获取所有类别和属于该类别的帖子,要获取所有类别,我使用以下代码
$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
...
...
我基本上是在尝试获取所有类别和属于这一类别的所有类型文章的帖子,我尝试了许多不同的方法,但似乎没有任何效果,如何进行?
谢谢
最合适的回答,由SO网友:Ibrahim Azhar Armar 整理而成
我用以下代码解决了这个问题:
$currentCategoryId = wp_get_object_terms($post->ID, \'article-category\', array(\'fields\' => \'ids\'));
if (is_array($currentCategoryId) && !empty($currentCategoryId[0])) {
$currentCategoryId = (int)$currentCategoryId[0];
}
$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 );
$categories = array();
foreach ($get_categories as $index => $category) {
$categories[$index][\'id\'] = $category->cat_ID;
$categories[$index][\'slug\'] = $category->slug;
$categories[$index][\'name\'] = $category->name;
}
$articles = array();
foreach ($categories as $index => $category) {
$args = array(
\'post_type\' => \'article\',
\'post_status\' => \'publish\',
\'posts_per_page\' => -1,
\'tax_query\' => array(
array (
\'taxonomy\' => \'article-category\',
\'field\' => \'slug\',
\'terms\' => $category[\'slug\'],
)
)
);
$articles[$index][\'category\'][\'id\'] = $category[\'id\'];
$articles[$index][\'category\'][\'name\'] = $category[\'name\'];
$articles[$index][\'category\'][\'slug\'] = $category[\'slug\'];
$posts_array = get_posts( $args );
foreach ($posts_array as $key => $_post) {
$articles[$index][\'posts\'][$key][\'id\'] = $_post->ID;
$articles[$index][\'posts\'][$key][\'title\'] = $_post->post_title;
$articles[$index][\'posts\'][$key][\'permalink\'] = get_permalink($_post->ID);
}
}
wp_reset_postdata();