I'd need to fetch the title of a parent page on a page that shows a catalog of several pages, like this:

enter image description here

I know how to do displaying the parent page:

<p><strong><?php echo get_the_title( $post->post_parent ); ?></strong></p>

But I'm wondering how to make this happen only with certain parent pages, where showing the parent page title makes it more clear what the child page is about. For others, I wouldn't want to show it. I hope this makes sense.

I believe I should probably use <?php if (is_page() ) : ?> <?php endif; ?> somehow and wrap that around the whole thing, but I'm unsure about how to fit the syntax together since I'm not super familiar with php at this point. Can someone help me out?

  • 1
    And what is the condition for showing that parent page? – Krzysiek Dróżdż Nov 28 at 12:18
  • 2
    "where showing the parent page title makes it more clear what the child page is about" is a very subjective thing, I don't believe it can be programmed in without human intervention to flag those pages so that it has something to check against. Then you have a new problem, that some pages appear to not have a parent page when in fact they do have a parent page – Tom J Nowell Nov 28 at 12:18
  • Let me clarify. All those parent pages that I do want to display have a similar kind of title, which would make it relatively easy to filter them out. And to clarify another thing, I have several pages that use the same template, but I would want to display the parent page only on some pages using the template. I know I could just make a copy of the template and use that instead where I need it, but that would also cause some extra work and I was wondering if there's quicker way to accomplish what I want. – M.K. Nov 28 at 14:41

You're most of the way there with your current code - you're correct that you can wrap the condition around what you've already got. The is_page() function allows you to check for an array of pages, so as long as you plan to specify pages manually, all you need to do is

<?php if (is_page(array(11, 'about', 'Contact Us')) ) : ?>
    <p><strong><?php echo get_the_title( $post->post_parent ); ?></strong></p>
<?php endif; ?>

is_page() accepts page ID, slug (from the permalink), and title. You'll probably want to pick whichever of those makes the most sense to you personally and use the same piece of data for all the pages, just so it's easier to identify which pages it applies to if you come back to it later.

Do note that whatever code you write, you'll want to write it inside a child theme. That's because when you update your theme, it will overwrite any customizations you've done.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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