1

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>
            </li>
        <?php endforeach; ?>

    </ul>

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?) – Dave Romsey Nov 24 '16 at 2:53
1

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 – pealo86 Nov 25 '16 at 12:16
2

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.

<?php 
global $post;
$children = get_pages(array('child_of' => $post->ID)); 
?>
0

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

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