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
?>
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
usortfunction. Here’s an example:If you’re sure that all the categories are in your
$cat_orderarray, you can forgo the integer casting.P.S. If you’re using PHP < 5.2, use a named function instead: