Support » Fixing WordPress » How to call out all parent titles

  • I’m still really new to PHP. I would like to have the title of my pages show all parent categories. If in my navigation drop down menu, I have a category, sub-category and sub-sub category, I would like to see the directory in my page title (Ex: About > People > Name)

    So far I am able to call the page title and the parent title, but I’m not sure how to get my grandparent(?) title or anything above? (if that makes any sense)

    Thank you in advance!

Viewing 3 replies - 1 through 3 (of 3 total)
  • Hi,

    could you share your current code that you use for displaying parent title + actual page title, just to give me an idea how you’re setting it up.

    Thread Starter wpkimah

    (@wpkimah)

    Thanks for your response! Here’s the code on my page template.

    <div id="content"><?php the_post();?>
    			<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
    			<h1 class="entry-title"><?php $parent_title = get_the_title($post->post_parent);echo $parent_title;?> / <?php the_title(); ?></h1>
    			<div class="entry-content"><?php the_content(); ?>

    I have the pages nested under parent categories in wordpress. I don’t need these to link, I would just like to display the titles.

    Any ideas or suggestions are appreciated! 🙂

    Sorry for getting late back to you.

    I’ve written a small function for you, tested and working:

    function my_parent_pages_titles( $post = 0, $separator = ' / ', $parents = array() ) {
    
    	$post = get_post( $post );
    
    	if ( ! empty( $post->post_parent ) && 0 !== $post->post_parent ) {
    
    		$parent = get_post( $post->post_parent );
    
    		$parents[] = $parent->post_title;
    
    		return my_parent_pages_titles( $parent->ID, $separator, $parents );
    
    	} else {
    
    		$result = '';
    
    		$parents = array_reverse( $parents );
    
    		foreach ( $parents as $parent ) {
    
    			$result .= $parent . $separator;
    
    		}
    
    		return substr( $result, 0, - strlen( $separator ) );
    
    	}
    
    }

    You would call it like this in your loop:
    my_parent_pages_titles();

    or if you would like to change the separator (default is “/”):
    my_parent_pages_titles( $post, ' - ' );

    You can also get the parents out of the loop, by passing post id or post object as a first parameter
    my_parent_pages_titles( 1, ' - ' );

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘How to call out all parent titles’ is closed to new replies.