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:
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 -->
Since you already have the category ID (you use it in your call to
WP_Query::query()
), you can just use that to request the category name.get_cat_name( $cat_id )
will do exactly that. It usesget_category( $cat_id )
in the background, which returns the full category object, which can be useful if you want to show more information about the category.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.
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.. 😉