Reputation: 3243
I am using get_categories
to show posts in a category in my frontpage, but I want to order categories as i defined,Like:
$cat_order = 5,2,4,1,3 //order by category ID
or
$cat_order = cat5,cat2,cat4,cat1,cat3 // order by cat name
below is my current code which order cat by name, ASC
<?php
//for each category, show all posts
$cat_args=array(
'orderby' => 'name',
'order' => 'ASC'
);
$categories=get_categories($cat_args);
foreach($categories as $category) {
$args=array(
'showposts' => -1,
'category__in' => array($category->term_id),
'caller_get_posts'=>1
);
$posts=get_posts($args);
if ($posts) {
echo '<p>Category: <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> </p> ';
foreach($posts as $post) {
setup_postdata($post); ?>
<article >
<h3><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3>
<?php the_content(); ?>
</article>
<?php
} // foreach($posts
} // if ($posts
} // foreach($categories
?>
Upvotes: 1
Views: 797
Reputation: 219930
There's no way to sort this within the query itself. You'll have to sort it yourself once you get the results back. To sort an array by custom criteria, use the usort
function. Here's an example:
$categories = get_categories();
$cat_order = array(5, 2, 4, 1, 3);
usort($categories, function ($a, $b) {
return ((int) array_search($a->term_id , $cat_order)) - ((int) array_search($b->term_id , $cat_order));
});
If you're sure that all the categories are in your $cat_order
array, you can forgo the integer casting.
P.S. If you're using PHP < 5.2, use a named function instead:
function sort_categories ($a, $b) {
return ((int) array_search($a->term_id , $cat_order)) - ((int) array_search($b->term_id , $cat_order));
}
usort($categories, 'sort_categories');
Upvotes: 2