简体   繁体   English

WordPress的头文件包含文件不起作用

[英]WordPress include file at header not working

I tried to include some php files in header.php. 我试图在header.php中包含一些php文件。 I use the script below :- 我使用以下脚本:-

get_template_part( 'custom/tos_functions');

However get_template_part doesn't work for me, so I use include which works fine. 但是get_template_part对我不起作用,因此我使用include可以正常工作。

include (TEMPLATEPATH . "custom/tos_functions.php");

The issue is, if I put this line in header.php, I want to use some of the functions in custom template , say profile.php. 问题是,如果我将这一行放在header.php中,我想使用自定义模板中的某些功能,例如profile.php。 In profile.php the file is as though not being called at all. 在profile.php中,该文件好像根本没有被调用。 I can't get the data I need in profile.php. 我无法在profile.php中获得所需的数据。

Then I tried to take out the include script from header, and place it in profile.php and the data I need can be called perfectly fine. 然后,我尝试从标头中取出包含脚本,并将其放在profile.php中,可以将我需要的数据称为完全正确。 This will be an issue as there will be many custom php pages I need to create, thus every page will call the include script. 这将是一个问题,因为我需要创建许多自定义php页面,因此每个页面都将调用include脚本。

Question, why is it that the file cannot be called from header.php ? 问题,为什么不能从header.php调用文件? The data can only be retrieved within header.php and any custom page that calls the header, couldn't get the data from the include file. 只能在he​​ader.php中检索数据,而任何自定义页调用页眉都无法从包含文件中获取数据。

Anyway I can fix this so that I can place the include file in the header.php? 无论如何,我可以解决此问题,以便将包含文件放置在header.php中?

Thank you! 谢谢!

Rather than including files in the theme template files (such as header.php ), you should include them in the theme's functions.php file. 您不应将文件包括在主题模板文件中(例如header.php ),而应将它们包括在主题的functions.php文件中。

Including them in the template files is almost always too late in the WP run for it to be useful, and it may cause unexpected results and unexpected output in your templates. 在WP运行中将它们包括在模板文件中几乎总是为时已晚,以至于无法使用,并且可能会导致模板中出现意外结果和意外输出。

Instead, in your functions.php file, do something like so: 相反,在您的functions.php文件中,执行以下操作:

require_once 'custom/tos_functions.php';

Then, your API code is available where you need it, and it is in the "right" place and consistent with the "WordPress way". 然后,您的API代码可在需要的地方使用,并且在“正确的”位置并与“ WordPress的方式”保持一致。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM