0

I'm working on a template-part called heading which displays the page heading and an optional subtitle underneath. I have it working on pages, but on archive pages like our blog or product category pages, it returns the first matching post title.

Here's the code:


$id = get_the_ID();
$heading = get_the_title();
$sub_heading = get_field('sub_heading', $id);


if (is_home() || is_category()) {
    $heading = get_the_title(12);
    $sub_heading = 'Learn, Modify, Create.';
} else if (is_404()) {
    $heading = '404';
    $sub_heading = "Well, this is awkward.";
} else if (is_shop()) {
    $heading = 'SHOP';
    $sub_heading = "Explore our complete product offering here";
} else if (is_product_category()) {
    $sub_heading = category_description();
}

?>

<div class="page-heading-section-wrapper">

    <div class="page-heading-section">

        <h1 class="main-heading"><?php echo $heading; ?> </h1>

        <?php if ($sub_heading) {
            echo '<h2 class="sub-heading">' . $sub_heading . '</h2>';
        }; ?>

    </div>

</div>

Example:

If I had a product category of "Balloons" and my products within it were "Birthday", "Holiday" etc, the title on the archive page would be "Birthday". The category description seems to work fine.

What am I doing wrong?

1
  • there's no code showing how the template is being called in context, can you edit that into your question?
    – Tom J Nowell
    Jan 11, 2022 at 14:04

1 Answer 1

1

For categories/taxonomies you can use get_queried_object to get the current category. From there you can easily get the name. So from your example:

if ( is_category() ) {
    $cat = get_queried_object();
    $heading = $cat->name;
}
3
  • So I was just able to fix it using get_the_archive_title(). Is there a benefit to your way?
    – sackadelic
    Jan 11, 2022 at 13:53
  • This way won’t work. get_the_title() cannot get archive titles. Jan 11, 2022 at 14:07
  • @JacobPeattie Yes, you are right! My answer was too fast. I edited my answer. Thanks for pointing it out!
    – DeltaG
    Jan 11, 2022 at 14:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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