0

I am, admittedly, a little new to PHP, and I'm trying to get a handle on loops. I'm working on an archive page for a comic website. These comics are broken up into Books, and further broken up into Chapters. I created a custom taxonomy called "Books" and created terms called chapters that have slugs reflecting which book they belong to, such as book-1-chapter-1 (and then there's also a book-2-chapter-1).

I would like to show the title of the chapter, which is the name of the term, but I'm struggling with that. I would like to show the name of the taxonomy term being called, and then loop links to any posts under that. The code is below. My loop works as it's supposed to, but I haven't had luck calling the title. I'd also like the title to not show at all if there are no posts in that category.

<h2>Book 01</h2>
    <?php
        $args = array( 
           'post_type' => 'comic',
           'book' => 'book-1-chapter-1',
           'order' => 'asc'
        );
        $the_query = new WP_Query( $args );
    ?>
    <h3><!-- Looking to add custom taxonomy term title here --></h3>
    <ul class="archive-list">&ndash;
        <?php if ( have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <li><a href="<?php the_permalink() ?>"><?php the_title();?></a>&nbsp;&nbsp;&ndash;</li>
        <?php endwhile; endif; ?>
    </ul>

Any help would be appreciated. If there's a better way to do this I'm open to that too. Like I said, I'm still learning!

1

You can use single_term_title():

<h3><?php single_term_title(); ?></h3>

To hide it if there are no posts, use the if ( have_posts() ) : function:

<?php if ( have_posts() ) : ?>
    <h3><?php single_term_title(); ?></h3>
<?php endif; ?>

If not an archive, you can use get_term_by() to get the term object for the term and then echo the name:

$term = get_term_by( 'slug', 'book-1-chapter-1', 'book' );
?>

<h3><?php echo $term->name; ?></h3>
  • I tried putting that in, and it didn't work. I tried just using the H3 single_term_title() as well as the php if combo. – Echo Martin Oct 30 '17 at 3:59
  • that will work only for taxonomy archives, right? – inarilo Oct 30 '17 at 4:00
  • @EchoMartin I updated my answer for getting the title outside of archives. – Jacob Peattie Oct 31 '17 at 11:24
  • @JacobPeattie That worked for getting the name! Unfortunately, it still shows the h3 even without posts present. I tried wrapping it in the code you gave before to hide it if there are no posts, but still won't hide. – Echo Martin Oct 31 '17 at 19:40
  • 1
    It works perfectly now, exactly as intended. Thank you SO much for your help! – Echo Martin Nov 1 '17 at 11:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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