php 列出根和子类别,包括他们发布的帖子
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 列出根和子类别,包括他们发布的帖子相关的知识,希望对你有一定的参考价值。
<?php
$post_type = 'products';
$taxonomy = 'products-category';
// Fetch root categories
$root_cat_args = array(
'taxonomy' => $taxonomy,
'hide_empty' => false,
'parent' => 0,
'post_status' => 'publish',
);
$root_categories = get_categories($root_cat_args);
foreach ($root_categories as $category) {
// Print root category titles
printf('<h1 style="color:red;">%s</h1>', $category->slug);
// Fetch root category posts
$root_posts_args = array(
'post_type' => $post_type,
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'term_id',
'include_children' => false,
'terms' => $category->term_id,
),
),
);
$root_posts = new WP_Query($root_posts_args);
foreach ($root_posts->posts as $post) {
// Print root category posts
printf('<h2 style="color:brown;">- %s</h2>', $post->post_title);
}
// Fetch sub categories
$sub_cat_args = array(
'taxonomy' => $taxonomy,
'hide_empty' => false,
'parent' => $category->term_id,
'post_status' => 'publish',
);
$sub_categories = get_categories($sub_cat_args);
foreach ($sub_categories as $category) {
// Print sub category titles
printf('<h1 style="color:cyan;">- %s</h1>', $category->slug);
// Print all posts of this sub category
$sub_posts_args = array(
'post_type' => $post_type,
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'term_id',
'include_children' => false,
'terms' => $category->term_id,
),
),
);
$root_posts = new WP_Query($sub_posts_args);
foreach ($root_posts->posts as $post) {
// Print root category posts
printf('<h2 style="color:brown;">-- %s</h2>', $post->post_title);
}
}
}
以上是关于php 列出根和子类别,包括他们发布的帖子的主要内容,如果未能解决你的问题,请参考以下文章
php Wordpress - 列出所有(自定义帖子类型)帖子类别
php 在wordpress中按类别列出帖子
PHP 查询帖子 - 按类别列出
PHP 按类别列出WordPress帖子
类别和子类别架构设计
在 WooCommerce 订单页面上列出单独购买的产品的类别和子类别