[英]How can I conditionally include PHP files for the homepage only, through functions.php
我需要require_once
從lib文件夾中的PHP文件在我的主題,但只是在着陸頁這也是博客/后索引頁。
當我將require_once
代碼單獨添加到functions.php時,它可以正常工作,但在所有頁面和我需要防止的單個帖子中也可以執行。
當我添加以下條件查詢標記時,它們似乎被忽略並且該文件未包含在主頁上。
if ( is_front_page() && is_home() ) {
require_once 'lib/example.php';
}
我缺少什么,推薦的方法是什么?
注意:這必須添加到主題的functions.php文件中。
如果您的代碼包含在functions.php的正文中,則它將無法正常工作,因為它在所有准備就緒的is_home
或is_front_page
正常工作之前is_home
加載。 您需要加入之后發生的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_page
和is_home
。 如果您在WP管理員設置中更改了首頁或帖子頁面,則同時使用這兩項檢查可能會破壞您的預期功能。 參考 : Wordpress Codex條件標簽 :
警告 :您只能在WordPress中的posts_selection 操作掛鈎之后使用條件查詢標記(wp操作掛鈎是您可以使用這些條件查詢的第一個)。 對於主題,這意味着如果您在functions.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();
之前的header.php中添加此代碼wp_head();
if ( is_front_page() && is_home() ) {
require_once( get_stylesheet_directory() . '/lib/example.php' );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.