問題描述

我的問題是在主要的插件文件我包括一個這樣的 PHP 文件:

include(WP_PLUGIN_URL . '/wordpress-group-buying/ipn/paypal-ipn.php');
// or
include_once(WP_PLUGIN_URL . '/wordpress-group-buying/ipn/paypal-ipn.php');
// or
require(WP_PLUGIN_URL . '/wordpress-group-buying/ipn/paypal-ipn.php');
// or
require_once(WP_PLUGIN_URL . '/wordpress-group-buying/ipn/paypal-ipn.php');

在這個文件上我有一個 WordPress 函數的調用,如:

add_action('hook', 'callback');

我得到:

Fatal Error: Call to undefined function add_action()

現在在你説 「使用 if(**function_exists**('add_action')){」 之前,如果我使用那麼它只是不工作。

問題:

  • 這樣做的正確方法是什麼?
  • includeinclude_oncerequire 和什麼時候使用巫婆有什麼區別?

最佳解決方案

遲到的這個聚會,但這裏是”WordPress” 的方式:使用 plugin_dir_path( __FILE__ ),例如:

<?php
include( plugin_dir_path( __FILE__ ) . 'ipn/paypal-ipn.php');
?>

請注意,該函數確實返回文件路徑的尾部斜線。

次佳解決方案

我查看了我之前創建的幾個插件,以查看不同的方式,我已經在插件中添加了額外的文件,我注意到有兩種方法可以使用,可能更多。

定義你的插件目錄

您的插件內部有以下定義來定義當前的插件位置。

示例代碼:

define( 'PLUGIN_DIR', dirname(__FILE__).'/' );

只是一個直線包括或要求

你可以簡單地使用; 通過引用下面的示例代碼中的位置,在您的插件文件夾中包含 include_once,require 或 require_once 。以下示例將基於您的根插件目錄中的一個文件,包括您的插件文件夾內的文件夾中的另一個文件。

示例代碼:

include "classes/plugin-core.php";

第三種解決方案

我最終將 for WordPress 構造用於包含並使用以下內容:

require_once(dirname(__FILE__) . '/filename.php);

我不認為它會真正解決你的問題,這似乎是一個範圍問題,但它是我使用的代碼。

至於 include 和 require 之間的區別:如果沒有找到文件,include 將會發出警告如果沒有找到該文件,則會拋出一個致命錯誤

如果 include_once 和 require_once 已經被包含/必需,則不再包含/要求文件/代碼 (請注意,據我所知,這僅適用於特定目錄中的特定文件) 。

第四種方案

首先,感謝所有回答的人,

我的問題是調用包含完整的 url 的文件,這樣他們不會通過 WordPress 。這是因為我在主題插件文件中提到這個問題。所以修復最後使用:

include_once('/ipn/paypal-ipn.php');

我在 WordPress support 閲讀。再次感謝您的回答!

第五種方案

Include

The include() statement includes and evaluates the specified file.

Include Once

The include_once() statement includes and evaluates the specified
file during the execution of the
script. This is a behavior similar to
the include() statement, with the only
difference being that if the code from
a file has already been included, it
will not be included again. As the
name suggests, it will be included
just once.

Require

require() and include() are identical in every way except how they
handle failure. They both produce a
Warning, but require() results in a
Fatal Error. In other words, don』t
hesitate to use require() if you want
a missing file to halt processing of
the page.

Require Once

The require_once() statement includes and evaluates the specified
file during the execution of the
script. This is a behavior similar to
the require() statement, with the only
difference being that if the code from
a file has already been included, it
will not be included again.

上面的信息來自於 PHP 文檔,事情是沒有一個正確的,將依賴於代碼的需要,我對 require() 在重要的東西就像函數,但是在主題文件,如頁腳或循環我使用 include_once 或 include,因為我可以處理警告,並向用户/訪問者發出發生錯誤,而不是隻是一個 fatal_error

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。