問題描述

我得到了基本的插件概念。我已經閲讀了關於 Writing a Plugin 的法典文章

那篇文章談到 「主要的插件文件」 。

WordPress 如何確定 「主要的插件文件」?

Q1:是否合法/支持有一個這樣的結構的插件:

  • pluginname /

  • pluginname /mainfile.php 中

  • pluginname /supportingcode-1.PHP

  • pluginname /supportingcode-2.PHP

  • pluginname /的 Readme.txt

  • 等等..

Q2:如果是這樣,wordpress 如何確定哪個 php 文件是主要的插件文件?


我已經看到建議説 「我以這種方式構建我的代碼」:

  • pluginname /

  • pluginname /mainfile.php 中

  • pluginname /INC /supportingcode-1.PHP

  • pluginname /INC /supportingcode-2.PHP

  • pluginname /的 Readme.txt

  • 等等..

Q3:當 PHP 代碼跨多個模塊時,是否使用子目錄 (如上例中的 inc/)?

Q4:主插件目錄中是否應該有最多一個 php 文件?

謝謝。

最佳解決方案

How does WordPress determine “the main plugin file” ?

這是您的插件中包含插件標題註釋的文件

/**
 * Plugin Name: A fresh example
 * Plugin URI:  http://example.com
 * Description: Foo makes a bar
 * Version:     2012-06-14.1426
 * Author:      John Doe
 * Author URI:  http://example.com
 * TextDomain:  your_textdomain
 * License:     MIT
 * LicenseURI:  http://www.opensource.org/licenses/mit-license.php
 */

Q1: Is it legal / supported to have a plugin that is structured like this:

是。每個目錄結構 (只要服務器支持) 是合法的。

Q2: If so, how does wordpress determine which php file is the main plugin file?

見上面↑

Q3: Is the use of a subdirectory (like inc/ in the above example) a requirement when the PHP code spans multiple modules?

需求?不太好看:是的。更容易維護:也可以。

Q4: Is it true that there should be a maximum of ONE php file in the main plugin directory?

不,沒有。

總結

您完全組織文件和目錄的方式取決於您,您的個人喜好,而無其他事項。如果你想讓你更容易維護和其他開發人員逐步執行你的代碼,那麼你應該使用某種文件/目錄組織。

例子

當我上課時,我個人將.class.php 作為擴展名。我也命名我的文件正好像課。原因很簡單:我的 「主要插件文件」 – 這是我的 bootstrap 類,通常關心加載所有需要的東西。

// inside my PREFIX_bootstrap class:
public static $includes = array(
    'settings'          => false // Parent class - no need to hook
   ,'settings_extended' => true  // Extending class - hooks static init() on `init` hook
);

public function construct()
{
    // The prefix for every class in my plugin
    $prefix = 'my_class_prefix_';

    foreach ( $this->files as $handle => $hook )
    {
        require_once plugin_dir_path( __FILE__ )."{$handle}.class.php";

        if ( ! $hook )
            continue;

        $class = $prefix.$handle;
        class_exists( $class ) AND add_action( 'init', array( $class, 'init' ), 1 );
    }
}

這意味着我的類和文件的命名如下:

  • settings.class.phpsettings_extended.class.php

  • my_class_prefix_settingsmy_class_prefix_settings_extended

我也做一些基本的目錄組織,比如將所有 js/css/img 文件存儲在這樣的目錄中。

有些人使用名為 inc/includes/assets/extensions/lib/etc. 的大型插件文件夾。我建議僅使用子文件夾進行大型插件。如果你有其他的東西,如小工具等,那麼你可以為他們使用特定的子文件夾。

最後一句話:不,沒有什麼你發現是真的,那些 (像我顯示的東西) 只是建議。

參考文獻

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