問題描述

我正在編寫一個插件,bar,它取決於另一個插件,foo,被激活,並且我需要從 foo 的功能在 bar 加載時可用。通常根據目錄名稱按字母順序加載插件,所以 bar 在 foo 之前加載。如果我將 bar 目錄重命名為 zbar,那麼它最後被加載並且工作正常,但是我正在尋找一個更加優雅和正確的解決方案。

我遵循了 jsdalton 的改變 active_plugins 選項的方法,並且重新排序數組以在最後放置條,但是在實例化時,bar 仍然無法訪問 foo 的功能。我已經閲讀了相關的核心代碼 – 基本上是 wp-settings.phpwp-includesload.php 中的 wp_get_active_and_valid_plugins(),而且它似乎是按照 active_plugins 索引的順序加載插件,所以我無法弄清楚出了什麼問題。

這是在 MultiSite 安裝。酒吧是一個課程,foo 是程序性的。

這是一個 stripped-down 版本的 foo /foo.php

function foo()
{
    // stuff
}

這是一個 stripped-down 版本的 bar /bar.php

class bar
{
    public function __construct()
    {
        // ...

        $active_plugins = get_option('active_plugins');
        print_r($active_plugins);

        if( function_exists('foo') )
            wp_die("foo exists");
        else
            wp_die("foo doesn't exist yet");
        }
    }
}

function this_plugin_last()
{
    $wp_path_to_this_file = preg_replace('/(.*)plugins/(.*)$/', WP_PLUGIN_DIR."/$2", __FILE__);
    $this_plugin = plugin_basename(trim($wp_path_to_this_file));
    $active_plugins = get_option('active_plugins');
    $this_plugin_key = array_search($this_plugin, $active_plugins);

    if ($this_plugin_key)
    {
        array_splice($active_plugins, $this_plugin_key, 1);
        array_push($active_plugins, $this_plugin);
        update_option('active_plugins', $active_plugins);
    }
}
add_action("plugins_loaded", "this_plugin_last");

$bar = new bar();

這是 bar 的構造函數的輸出:

Array
(
    [0] => foo/foo.php
    [1] => bar/bar.php
)

foo doesn't exist yet

最佳解決方案

不要觸摸加載順序,改變激活順序。一個工作實例可以在 this answer 中找到。

次佳解決方案

無論什麼,您的構造函數將始終在代碼中調用操作之前運行。

我曾經遇到過這種情況,你們大多是在那裏做的。

簡單的説 – 把 this_plugin_last 功能裏面的一切註釋掉,並把你的 $ bar = new bar(); 裏面有並且只需在該函數中執行所需的所有邏輯和所需要的內容。這樣可以確保在運行代碼之前加載 foo(插件本身並不一定需要在手之前加載,而是依賴於 foo 使用的) 。

參考文獻

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