問題描述

我的問題是在主要的外掛檔案我包括一個這樣的 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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。