WP Plugin開發 (1)-Plugin 起始設定

文章參考:https://codex.wordpress.org/Writing_a_Plugin

檔案&目錄

建立Plugin第一件事就是命名,要取一個獨一無二的外掛名稱,不然跟別的名稱衝到就會發生慘案了
Plugin的資料夾是在 wp-content/plugins/ 
如果我的Plugin名稱為 MyFristPlugin
就在 wp-content/plugins/ 中建立一個資料夾 MyFristPlugin
然後在資料夾中建立一個 MyFristPlugin.php 的主程式

readme.txt

如果要把自己的plugin發布上傳到官網給大家下載,包裝檔案內一定要包含readme.txt

readme.txt 範本:https://wordpress.org/plugins/readme.txt

更改後可以透過驗證器檢查內容
https://wordpress.org/plugins/developers/readme-validator/

更多發布細節請參考:https://wordpress.org/plugins/developers/

MyFristPlugin.php 的檔案開頭一定要加上 File Headers 自我介紹
Header設定可以參考:https://developer.wordpress.org/plugins/plugin-basics/header-requirements/

<?php
/**
 * Plugin Name:       My Frist Plugin
 * Plugin URI:        http://www.gocar.idv.tw/plugins/MyFristPlugin/
 * Description:       我的第一個Plugin
 * Version:           1.0
 * Author:            Henry Tsai
 * Author URI:        http://www.gocar.idv.tw/
*/

?>

通常 Header 除了自我介紹外還會加入版權宣告
https://developer.wordpress.org/plugins/plugin-basics/including-a-software-license/

所以完整的Header就像這樣

/**
 Plugin Name:       My Frist Plugin
 Plugin URI:        http://www.gocar.idv.tw/plugins/MyFristPlugin/
 Description:       我的第一個Plugin
 Version:           1.0
 Author:            Henry Tsai
 Author URI:        http://www.gocar.idv.tw/

 {Plugin Name} is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 any later version.
  
 {Plugin Name} is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 GNU General Public License for more details.
   
 You should have received a copy of the GNU General Public License
 along with {Plugin Name}. If not, see {License URI}
*/

設定好後在已安裝的外掛清單中就可以看到剛儲存的外掛


環境配置:

一般plugin資料夾中我會建立下列目錄
同時會用 plugin_dir_path() & plugins_url() 來做路徑的設定

wp-content/plugins/MyFristPlugin
wp-content/plugins/MyFristPlugin/includes
wp-content/plugins/MyFristPlugin/js
wp-content/plugins/MyFristPlugin/css
wp-content/plugins/MyFristPlugin/images

利用 plugin_dir_path() 來 include 檔案:

define('MY_FRIST_PLUGIN_PATH', plugin_dir_path( __FILE__ )); // plugin所在目錄
define('MY_FRIST_PLUGIN_PATH_INCLUDES',MY_FRIST_PLUGIN_PATH.DIRECTORY_SEPARATOR.'includes'.DIRECTORY_SEPARATOR); // include 檔所在目錄

require_once MY_FRIST_PLUGIN_PATH_INCLUDES . 'function.php'; // 載入檔案

利用 plugins_url() 載入 js 檔或 css

<link rel='stylesheet' id='my-css' href='<?php echo plugins_url( '/css/my.css' , __FILE__ ); ?>'>' type='text/css' media='all' />
<script type='text/javascript' src='<?php echo  plugins_url( '/js/script.js' , __FILE__ ); ?>'></script>

基本的環境配置好了,下一步就開始製作程式囉

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。