Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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(', ') ?>
share|improve this question
    
Which function? –  Krzysiek Dróżdż Jul 12 '13 at 9:29
    
<?php the_category(', ') ?> –  Shabbir Lakdawala Jul 12 '13 at 9:35
add comment

1 Answer

up vote 1 down vote accepted

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

share|improve this answer
    
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 Jul 12 '13 at 11:20
    
yups sorry i deleted the comment i was adding space after , so it was not able to trim. –  Shabbir Lakdawala Jul 12 '13 at 11:22
    
If you are adding space after comma, then modify the last line as echo trim( trim($output), "," ); :) dirty! –  webdwall Jul 12 '13 at 11:26
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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