如何通过函数有条件地仅为主页包含 PHP 文件.php



我需要从主题中的lib文件夹中require_once一个php文件,但只能在登录页面中,这也是博客/帖子索引页面。

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

当我添加以下条件查询标签时,它们似乎被忽略了,并且该文件不包含在主页上。

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

我错过了什么,推荐的方法是什么?

注意:这必须添加到主题的功能.php文件中。

如果代码包含在函数主体中,则代码将无法正常工作.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:

警告:您只能在 WordPress 中的posts_selection操作钩子之后使用条件查询标签(wp 动作挂钩是您可以使用这些条件的第一个钩子)。对于主题,这意味着如果您在函数主体中使用它.php即在函数外部)将永远无法正常工作。

您需要将 && 替换为 ||

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

要么使用

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

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

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

wp_head();之前将此代码添加到标头.php

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

最新更新