最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

include - How to pass variables with get_template_part?

programmeradmin1浏览0评论

I am developing a custom theme and i like to pass some variables to selected files. I am calling the view files from functions.php.

$var1 = ;
$var2 = ;
etc
include_once('form-views/view-profile.php');//works

//get_template_part('includes/form-views/view','profile');//doesn't work

Now with include it works

I am developing a custom theme and i like to pass some variables to selected files. I am calling the view files from functions.php.

$var1 = ;
$var2 = ;
etc
include_once('form-views/view-profile.php');//works

//get_template_part('includes/form-views/view','profile');//doesn't work

Now with include it works

Share Improve this question asked Oct 7, 2014 at 11:13 alexalex 1,1123 gold badges17 silver badges39 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 1

This is essentially scope visibility issue. include brings code into a current scope, function call creates new closed off scope. In get_template_part() only certain WordPress globals are being made available by load_template() call inside.

While the basic answer is to declare your variables as globals, you might want to ponder your overall architecture a bit — this is typically not a good sign in code.

In these cases, I usually use:

include(locate_template('includes/form-views/view-profile'));

In this way, a child theme can override the file.

WordPress 5.5 allows passing $args to get_template_part. Apart from this function there are sets of template function which can now accept arguments.

get_header
get_footer
get_sidebar
get_template_part_{$slug}
get_template_part

Please refer more details at: https://make.wordpress/core/2020/07/17/passing-arguments-to-template-files-in-wordpress-5-5/

发布评论

评论列表(0)

  1. 暂无评论