0

Iam using this wp function to show category in my post

I have certain post where i put the same post in two categories

It is showing alphabetically, I want to show first parent then child category.

EDIT:

<?php the_category(', ') ?>
2

1 Answer 1

1

The following code will print out all the top-level categories first and then all the non-top-level categories, if that's what u wanted.

<?php 
$categories = get_the_category( get_the_ID() );
if( $categories ){
    $output = "";

    //display all the top-level categories first
    foreach ($categories as $category) {
        if( !$category->parent ){
            $output .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '" >' . $category->name.'</a>,';
        }
    }

    //now, display all the child categories
    foreach ($categories as $category) {
        if( $category->parent ){
            $output .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '" >' . $category->name.'</a>,';
        }
    }

    echo trim( $output, "," );
}
?>

So you can use the above code instead of the_category()

3
  • Are you sure? Coz, the code already has trim( $output, "," ), which is supposed to remove the last comma. And i just checked it .. works... Make sure that the comma is not the result of something other than this code.
    – webdwall
    Commented Jul 12, 2013 at 11:20
  • yups sorry i deleted the comment i was adding space after , so it was not able to trim. Commented Jul 12, 2013 at 11:22
  • If you are adding space after comma, then modify the last line as echo trim( trim($output), "," ); :) dirty!
    – webdwall
    Commented Jul 12, 2013 at 11:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.