Here is a section of code that I have in a template file — to display sub-navigation if the page has child-pages:

<?php // display sub-nav if page has children ?>
<?php $children = get_pages(array('child_of' => $post->ID)); ?>
<?php if (count($children)) : ?>

    <ul class="nav nav-tabs">

        <?php foreach ($children as $val) : ?>
            <li role="presentation">
                <a href="<?php echo get_permalink($val->ID); ?>"><?php echo $val->post_title; ?></a>
        <?php endforeach; ?>


The code works fine when in the template file page.php, but if I put it all into a new file — nav.php and then include it with <?php get_template_part( 'include', 'nav' ); ?> then it stops working.

How can I set it so that the $post variable still works? Do I need to do something with global variables?

  • Where is nav.php located in your theme? (Is it in the root directory of the theme or a subdirectory?) Nov 24 '16 at 2:53

is your file name is 'include-nav.php' or it is placed inside 'include' folder ?

if not then simply call it by passing name of nav.php

<?php get_template_part( 'nav' ); ?>

you don't have to pass include keyword to call template.

Hope this help :)

  • turns out I actually forgot to include the include- at the start of my filename for the template part! got it working now thanks
    – user39214
    Nov 25 '16 at 12:16

get_template_part() calls your template file via require() but it does this inside of a function call. This means, it happens in a new variable scope. To make $post accessible again just use the global keyword.

global $post;
$children = get_pages(array('child_of' => $post->ID)); 

Existing variables will be accessible from within the included template if you wrap locate_template() inside an include statement:

include( locate_template( 'nav.php' ) );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy