user3550879
user3550879

Reputation: 3469

displaying 'category' of post in header tag

My Wordpress posts have categories (done through the admin panel) I want I have the post showing and want my h2 title to show the category. I can only find the <h2><?php single_cat_title(); ?></h2>function when i research which isn't working.

html

<?php the_title( '<h1>', '</h1>' ); ?>

<h2>  category name </h2>

<p> .......  </p>

Upvotes: 0

Views: 1240

Answers (1)

scytale
scytale

Reputation: 1399

I may have misunderstood your question but get_the_category() works outside the loop (loop see bottom) and I use it in a plugin.

It returns an array of category related elements for the current (by default) post.

Possible code for your usecase (not tested)

  1. If your posts are only ever associated with one category and code is in post template (depends on theme):

    <?php 
    the_title( '<h1>', '</h1>' );
    $categories = get_the_category();
    if ( ! empty( $categories ) ) {
      echo '<h2>' . esc_html( $categories[0]->name ) . '</h2>';   
    }
    ?>
    <p> .......  </p>
    
  2. if code is in header.php then likely and you only want your <h2> applied to posts:

    if (! is_front_page() && ! ..... ) { above code}
    
  3. posts can be associated with multiple categories in which case you may need to foreach the $categories for name and concatenate names, or determine which to use based on the category slug of the current post.

Within "the loop":

I'm not sure whether get_the_category() code above will work by default or whether post id is required as a parameter. The the_category() can ONLY be used in the loop - but this will give you an anchor link.

Upvotes: 1

Related Questions