Support » Fixing WordPress » change order of get_the_category()

  • Just something I learnt today that I thought I would share. Also anyone knows of a better way please let me know.

    A way to change the order of get_the_category.
    It normally dishes out the categories in alphabetical order. Even if you only want the cat_ID it still spits them out in an array based on how they are named.

    This can be annoying if you want to get the posts in the current category which is called Portfolio and also in Featured.

    anyway here we go.

    global $wp_query; //if outside of the main loop
    $cat_ID=array(); //create empty array
    $categories = get_the_category(); // get current posts categories
    foreach($categories as $category) {
    array_push($cat_ID,$category->cat_ID); // put the posts categories into the cat_ID array
    rsort($cat_ID); //sort the cat_ID array many different types of sort in PHP manual
    $category = $cat_ID[0]; // select the first value in the array
    $postlist = new WP_Query(“cat=$category”); // use that value in your query.
    while($postlist->have_posts()) :

  • The topic ‘change order of get_the_category()’ is closed to new replies.