Below is some basic code to call specficic categories to our front page post loop. It works fine, except my client wants the categories displayed in a particular order. I know there are other posts about this on the internet, but I didn’t see any that addressed it the way my client is asking.

Can I take the $categories variable, created in the code below, and just call those objects into a new array?

In this instance the objects all have a number in front of them, like :

[0] => values
[1] => values
[2] => values
....

when the output is dumped.

Can I take that output and just call them in the order I want them? (ex: 1,3,4,2,5,0)

Current code:

`

    wp_reset_postdata();        
    /* top stories end */           

     $args = array(

        'child_of'                 => 0,
        'parent'                   => '',
        'hide_empty'               => 1,
        'hierarchical'             => 1,
        'orderby'                  => 'id',
        'order'                    => 'ASC',
        'include'                  => '12,13,14,15,16,1',
    ); 

     $categories = get_categories( $args );
 ?>

<?php
    echo '<div class="home-all-cat">';
     foreach( $categories as $cat)
     {
        $slug = $cat->slug ;
        echo '<div class="home-cat-item" >'; 
        echo '<span class="cat-title">'.$cat->name.'</span><span class="cat-archive-link"><a target="_blank" href="'.get_category_link( $cat->cat_ID ).'" title="'.$cat->name.'">Show all '.$cat->name.'</a></span>';
        echo do_shortcode('[blog number_posts="6" cat_slug="'.$slug.'" exclude_cats="1" title="" thumbnail="" excerpt="" excerpt_words="20" meta_all="no" meta_author="" meta_categories="" meta_comments="" meta_date="" meta_link="" paging="" scrolling="" strip_html="" blog_grid_columns="" layout="medium"][/blog]');
        echo '</div>';

     }
     echo '<div class="clear">';
     echo '</div>';
 ?>

`

2 Answers
2

I think the most sane way and easiest way of doing this is to unset the first value in the returned array, and then adding it back at the end of the returned array before your foreach loop

For this to work, you will need to sort your categories by ID as you need to take category ID 1 and add that to the back. Something like this will work

<?php
$args = array(
    'hierarchical'             => 1,
    'orderby'                  => 'id',
    'order'                    => 'ASC',
    'include'                  => '13,21,41,1',
); 

$categories = get_categories( $args );

$v = $categories[0];
    unset($categories[0]);
    $categories[0] = $v;


foreach( $categories as $cat) {
    echo $cat->slug ;
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *