How do I get the title of a category in a custom loop?

I am using the following code to display a list of posts within a category, but I want to display the title in it’s own h2 tag above the list.

<ul class="subcats-list">
<?php
$weightloss = new WP_Query();
$weightloss->query('showposts=5&include=4');

while ($weightloss->have_posts()) : $weightloss->the_post(); ?>
    <li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
<?php endwhile; ?>

</ul><!-- subcat -->

EDIT:

Read More

So I tried using single_cat_title , however, the title is coming up for the parent category for all the sub category divs. Here’s an example of a div that I am replicating multiple times, where the query is pulling posts from different sub categories. I would like the title for each sub category above the posts. I realize it’s not working because I’m returning the parent category with that function, I’m just can’t figure out the php…

        <ul class="subcats-list">
            <h2 class="subcats-title"><?php single_cat_title(); ?></h2>
                <?php
                $weightloss = new WP_Query();
                $weightloss->query('showposts=5&cat=4');

                while ($weightloss->have_posts()) : $weightloss->the_post(); ?>
                  <li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
                <?php endwhile; ?>

        </ul><!-- subcat -->

Related posts

Leave a Reply

2 comments

  1. It’s not entirely clear what you’re referring to, you asked how to get the title of category inside a custom loop. Are you referring to particular category, or a category associated with a given post inside that loop?

    In any case if you’re referring to printing out the name of the first category for each post in your custom loop simply add the following code somewhere inside your loop.

    <?php single_cat_title(); ?>
    

    Documentation for the function can be found here:
    http://codex.wordpress.org/Function_Reference/single_cat_title

    Note the comment under your question though, that’s a valid point, what were you intending with the include parameter, are you trying to filter that query to a particular set of posts?

    Valid query parameters can be found on the WP_query codex page, if it’s helpful. If you’re unsure about how to set parameters, just let us know.. 😉