不必设置多个循环的一种快速方法是使用get_posts()
函数并抓取所有页面,然后使用in_category()
并将属于该类别的页面与不属于该类别的页面分开。
然后,您可以使用一个简单的foreach循环分别在ULs中运行这两组页面。
<?php $args = array(
\'post_type\' => \'page\',
\'post_status\' => \'publish\',
\'numberposts\' => -1
);
//Pull pages into an array
$all_pages = get_posts($args);
//Create empty arrays to populate with filtered pages
$in_category = array();
$ex_category = array();
//loop through the page array
foreach($all_pages as $post) {
//Set data from the current page as globals,
//to enable WordPress function tags
setup_postdata($post);
//Build the format of the link to be returned
$link_format = \'<li><a href="\'.get_the_permalink().\'">\'.get_the_title().\'</a></li>\';
//Check whether the page is in the category and
//send this link to the relevant array
if(in_category(4)) {
$in_category[] = $link_format;
} else {
$ex_category[] = $link_format;
}
};
//Restore postdata to before we set it to the current post
wp_reset_postdata(); ?>
<ul class="links_in_category_4">
<?php foreach($in_category as $cat_link) echo $cat_link; ?>
</ul>
<ul class="links_not_in_category_4">
<?php foreach($ex_category as $cat_link) echo $cat_link; ?>
</ul>