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?

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

3 Answers 3

0

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 :)

1
  • 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
    Commented Nov 25, 2016 at 12:16
1

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 and acknowledge you have read our privacy policy.