如果需要嵌套查询,首先应该考虑需要哪些数据。在您的示例中,您需要tanonomy的所有术语以及属于每个分类法的所有帖子。因此,第一步应该是找到一种循环遍历分类法所有术语的方法:
/* TAXONOMIES */
// args
$args_tax = array(
\'order\' => ASC);
// get terms
$terms = get_terms($tax, $args_tax);
$count = count($terms);
if ($count > 0) {
echo "<ul>";
foreach ($terms as $term) {
echo "<li>";
echo $term->name;
echo "</li>";
}
echo "</ul>";
}
http://codex.wordpress.org/Function_Reference/get_terms
在下一步中,您必须循环浏览帖子:
/* CPT POSTS */
// args
$args_cpt = array(
\'post_type\' => $cpt,
\'tax_query\' => array(
array(
\'taxonomy\' => $tax,
\'field\' => \'slug\',
\'terms\' => $term->slug
)
)
);
// get posts
$tax_query = new WP_Query($args_cpt);
if ($tax_query->have_posts()) {
echo "<ul>";
while ($tax_query->have_posts()) {
$tax_query->the_post();
echo "<li>";
echo get_the_title();
echo "</li>";
}
echo "</ul>";
}
wp_reset_postdata();
http://codex.wordpress.org/Class_Reference/WP_Query
现在必须将这两个循环组合起来。例如,在函数中放置的函数中。php:
/**
* RFRQ
* the_posts_by_tax
*/
if (!function_exists(\'the_posts_by_tax\')) {
function the_posts_by_tax($cpt, $tax) {
/* TAXONOMIES */
// args
$args_tax = array(
\'order\' => ASC);
// get terms
$terms = get_terms($tax, $args_tax);
$count = count($terms);
if ($count > 0) {
echo "<ul>";
foreach ($terms as $term) {
echo "<li>";
echo $term->name;
/* CPT POSTS */
// args
$args_cpt = array(
\'post_type\' => $cpt,
\'tax_query\' => array(
array(
\'taxonomy\' => $tax,
\'field\' => \'slug\',
\'terms\' => $term->slug
)
)
);
// get posts
$tax_query = new WP_Query($args_cpt);
if ($tax_query->have_posts()) {
echo "<ul>";
while ($tax_query->have_posts()) {
$tax_query->the_post();
echo "<li>";
echo get_the_title();
echo "</li>";
}
echo "</ul>";
}
wp_reset_postdata();
echo "</li>";
}
echo "</ul>";
}
}
}
您可以通过以下方式调用循环:
the_posts_by_tax($cpt, $tax)