2017-08-28 47 views
1

我需要require_once从lib文件夹在我的主题php文件,但只在着陆页这也是博客/后索引页。我怎么能有条件地仅包含网页PHP文件,通过functions.php的

当我将require_once代码自身添加到functions.php时,它可以正常工作,但也可以在需要防止的所有页面和单个帖子上执行。

当我添加下列条件查询标签,他们似乎被忽略,文件不包含在主页上。

if (is_front_page() && is_home()) { 
    require_once 'lib/example.php'; 
} 

我在想什么,推荐的方法是什么?

注:这必须添加到主题的functions.php文件。

+0

require_once在functions.php中完成,我忘了提及。 –

回答

2

您的代码将无法正常工作,因为它是如果包括它在functions.php的主体中,因为它在所有准备工作之前都会被加载,以便is_homeis_front_page正常工作。您需要勾选之后发生的其中一项Wordpress操作。

将下面的代码挂接到wp行动,那里的条件操作将工作:

// create a function to do the conditional check and include the files 
function include_files_homepage_only() { 
    if (is_front_page() && is_home()) { 
     require_once 'lib/example.php'; 
    } 
} 

// hook into the wp action to call our function 
add_action('wp', 'include_files_homepage_only'); 

注:

  • 头版和家庭(后索引页)在相同的您的网站 所以你并不需要检查,如果页面等于两个is_front_pageis_home。如果您在WP管理设置中更改了首页或帖子页面,则使用这两项检查可能会破坏您的预期功能。
  • 你应该使用正确的路径要包括的文件,例如 使用get_stylesheet_directory或get_template_directory作为 适当。

参考Wordpress Codex for Conditional Tags

警告:您只能在WordPress的(可湿性粉剂行动挂钩是第一位的,通过它,你可以使用这些使用条件查询标签posts_selection action hook后条件句)。对于主题,这意味着如果在functions.php主体中使用它,即在函数之外使用条件标签,它将永远不会正常工作。

+0

谢谢,那正是我所错过的。 –

-1

在header.php中添加此代码之前wp_head();

if (is_front_page() && is_home()) { 
    require_once(get_stylesheet_directory() . '/lib/example.php'); 
} 
0

您将需要||更换& &

if (is_front_page() || is_home()) { 
    require_once 'lib/example.php'; 
} 
+0

我们假设这两个函数检查了不同的东西,对吧?我不知道谁投票给你,但我投票给你回到零 – delboy1978uk

0

要么使用

if (is_front_page()) { 
    require_once 'lib/example.php'; 
} 

OR

if (is_home()) { 
    require_once 'lib/example.php'; 
} 

你不需要两者。 is_front_page() ---检查它是否是您网站的索引页。
is_home() ---检查,如果这是在设置中选择的博客页面(如果它不是在设置选择这将无法正常工作)

+0

这并不是从函数PHP工作,但工作,例如,来自index.php。我需要挂钩在functions.php中吗? WP在这个阶段不知道,当包含在functions.php中时,如果它是home或frontpage? –