WordPress.org

Ready to get started?Download WordPress

Forums

Detecting child page and showing parent title and subnav (4 posts)

  1. dgraydesign
    Member
    Posted 3 years ago #

    I've done a custom theme with top-level pages, each with their own child pages. I added a function is_child to my functions file and then added the following code to my page template - the goal is to detect if the page is a child page and, if so, display the parent page title and the subnav for that section:

    <?php
    if(is_child(32)) {
    $parent_title = get_the_title($post->post_parent);
    echo "<h6>$parent_title</h6>";
    }
    ?>
    <div id="sub-navigation">
    <?php
    if (is_child(32)){
    wp_nav_menu( array('menu' => 'Education Subnav' ));
    }
    ?>
    </div>

    This works fine, but I'm not very good at PHP and Im thinking there must be a more elegant solution. I couldn't get this to work without putting the page ID in the is child function. I'd like to know if there's a way to just have this code once, where it would detect the parent page and display the title and subnav without my having to repeat it with the page ID for each page. Thx for any help.

  2. dgraydesign
    Member
    Posted 3 years ago #

    A little more explanation - the 32 is the id of the parent page (that's the way the is_child function works.

  3. Hitesh Joshi
    Member
    Posted 3 years ago #

    I think you just need a function to do this? a function at functions.php file

    and call it whereever you need .
    <?php check_if_child(32,'Education Subnav'); ?>

    <?php
    function check_if_child($pageid,$thesubnav){
    global $post;
    if(is_child($pageid)) {
    $parent_title = get_the_title($post->post_parent);
    echo "<h6>$parent_title</h6>";
    }
    echo "<div id='sub-navigation'>";
    if (is_child($pageid)){
    wp_nav_menu( array('menu' => $thesubnav ));
    }
    echo "</div>";

    } ?>

  4. dgraydesign
    Member
    Posted 3 years ago #

    Thanks - I went ahead and launched the project with the code the way I had it, but I appreciate your response and I'll keep it for future reference.

Topic Closed

This topic has been closed to new replies.

About this Topic