Why would include(locate_template) work but not get_template_part()?

The parent theme uses this construct to include the navbar:

include(locate_template( "components/navigation.php" ));

I would prefer to use the WordPress convention:

get_template_part( "components/navigation" );

in my child theme, to call the file from the parent theme, but his code works and mine doesn’t. What am I doing wrong?

UPDATE:

The surrounding code looks like this:

if ( $navigation_type != '' ) {
  include(locate_template( "components/navigation.php" ));
}

This code loads fine, the debug log is empty. If I switch that code to

if ( $navigation_type != '' ) {
  get_template_part( 'components/navigation' );
}

then The debug log fills with
PHP Notice: Undefined variable: navigation_type in /path/to/components/navigation.php on line 31

1 Answer
1

when you use get_template_part, your file navigation.php cannot access variable $navigation_type. but when you do include and locate_template it is simply like including a php file so it can access that variable.
It is due to scope of variable in your context.

Leave a Comment