您可以通过以下方式获得所有类别:
$categories = get_categories( array ( \'fields\' => \'ids\' ) );
这将返回一个包含所有类别的数组。
那么你应该使用get_posts()
或anew WP_Query
, 因为query_posts()
有很多副作用,不应该再使用了。
示例代码,如图所示:
$categories = get_categories( array ( \'number\' => 5 ) );
print \'<pre>$categories = \' . htmlspecialchars( var_export( $categories, TRUE ), ENT_QUOTES, \'utf-8\', FALSE ) . \'</pre>\';
$boxes = array();
foreach ( $categories as $category )
{
$boxes[ $category->term_taxonomy_id ][\'posts\'] = get_posts(
array(
\'numberposts\' => 5,
\'category\' => $category->term_taxonomy_id,
\'posts_per_page\' => 3,
\'post_type\' => \'post\'
)
);
$boxes[ $category->term_taxonomy_id ][\'title\'] = $category->category_nicename;
}
foreach ( $boxes as $cat_id => $box )
{
printf(
\'<h2><a href="%1$s">%2$s</a></h2>\',
get_category_link( $cat_id ),
$box[\'title\']
);
print \'<ul>\';
foreach ( $box[\'posts\'] as $post )
printf(
\'<li><a href="%1$s">%2$s</a></li>\',
get_permalink( $post->ID ),
esc_html( $post->post_title )
);
print \'</ul>\';
}