change order of get_the_category() (1 post)

  1. amogle
    Posted 6 years ago #

    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()) :

Topic Closed

This topic has been closed to new replies.

About this Topic

  • RSS feed for this topic
  • Started 6 years ago by amogle
  • This topic is not a support question
  • WordPress version: 2.9.2