WordPress.org

Ready to get started?Download WordPress

Forums

Using <?php the_category; ?> w/ more than 2 categories (6 posts)

  1. Mischif
    Member
    Posted 6 years ago #

    OK, I'll try and be descriptive:

    When I put a blog post in one category, my <?php the_category; ?> tag works fine. When I put my blog post in two categories, my <?php the_category; ?> tag works fine, I just put an "and" in for the seperator, and everything still works just fine.

    Now here's my dilemma, what do I do when I have three or more categories? I want to have a comma in between every category except the last one, and then have an ampersand in the last one; i realize how to put the ampersand in for the last one, I'm just wondering if it's possible to have a comma for all but the last category, and an ampersand for the last category.

    Example:

    "This post is in the weird category" <- I can do this
    "This post is in the weird and awesome category" <- I can do this
    "This post is in the weird, awesome & funny category" <- Can I do this?
    "This post is in the weird, awesome, funny, super & amazing category" <- Can I do this?
    PS Is there a tag where I can display one word when my post is in only one category and another when my post is in more than one category?

  2. moshu
    Member
    Posted 6 years ago #

    "This post is in the weird, awesome & funny category" <- Can I do this?

    Not likely... unless you write your own code/plugin/blogging tool.

  3. Mischif
    Member
    Posted 6 years ago #

    aww...weak. I suppose I'll put that in for a feature request then.

  4. Mischif
    Member
    Posted 6 years ago #

    Well, how would I go about writing the PHP code?

  5. lucasbalzer
    Member
    Posted 6 years ago #

    the wordpress codex page http://codex.wordpress.org/Template_Tags/get_the_category
    gives the basic sample code, modified here for your particular dilemma:

    <?php
    $category_list_array=get_the_category();
    $last=count($category_list_array);
    $current=0;
    
    if ($last==1)
    echo $category_list_array[0]->cat_name;
    else if ($last==2)
    echo $category_list_array[0]->cat_name." and ".$category_list_array[1]->cat_name;
    else {
    foreach($category_list_array as $category){
    echo $category->cat_name;
    if ($current<$last-2)
    echo ", ";
    else if ($current==$last-2)
    echo " &amp; ";
    $current++;
    }
    }
    ?>
  6. Kafkaesqui

    Posted 6 years ago #

    I thought I recalled a plugin like this:

    http://txfx.net/2004/07/22/wordpress-conversational-categories/

    May even still work. :)

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags