用 ChatGPT 4o 寫 WordPress 外掛

用 ChatGPT 能快速產生 WordPress 外掛的基本結構(英文 skeleton )省去重複性工作,讓你專注於邏輯和功能設計。這篇文章會給你一個基本的提示詞只要貼上 chatGPT 即可產快外掛原始碼

提示詞

Build a WordPress plugin named ocam_related_post that uses Carbon Fields to create a Theme Options Page in the WordPress admin dashboard. The plugin should include three select fields:

1.Number Range – A select field with numeric options from 1 to 10.

2.Sort Order – A select field with the following options:

rand → Random Text

desc → Descending Text

asc → Ascending Text

3.Type Filter – A select field with the following options:

category → Text Category

tag → Text Tag

Ensure that Carbon Fields is properly initialized within the plugin, and the options page appears under Theme Options in the admin menu.

解釋

Carbon Fields:是 1 個原件能夠讓你快速的產出你要的欄位。

fields:欄位。因為 Carbon Fields 提供十數種不同的欄位選項。這邊得給 GPT 說明你要的欄位跟定義為何。範例中我選了 3 種。1:select 。值可由 1 到 10 個選項。2:也是 select 。值其 3 種。3:也是 select 值有 3 種。通常欄位的值跟你寫的程式有絕對的關係在使用提示詞前必需事先想好。

ChatGPT 產出

<?php
/**
 * Plugin Name: Ocam Related Post
 * Description: Adds a theme options page with select fields using Carbon Fields.
 * Version: 1.0
 * Author: Your Name
 */

use Carbon_Fields\Container;
use Carbon_Fields\Field;

defined('ABSPATH') || exit;

// Load Carbon Fields
add_action('after_setup_theme', function() {
    require_once plugin_dir_path(__FILE__) . '/vendor/autoload.php';
    \Carbon_Fields\Carbon_Fields::boot();
});

// Register the theme options
add_action('carbon_fields_register_fields', function() {
    Container::make('theme_options', __('Ocam Related Post Options', 'ocam_related_post'))
        ->set_icon('dashicons-admin-generic')
        ->add_fields([
            Field::make('select', 'ocam_number_range', __('Number Range'))
                ->set_options(array_combine(range(1, 10), range(1, 10)))
                ->set_default_value(5),

            Field::make('select', 'ocam_sort_order', __('Sort Order'))
                ->set_options([
                    'rand' => 'Random Text',
                    'desc' => 'Descending Text',
                    'asc' => 'Ascending Text',
                ])
                ->set_default_value('rand'),

            Field::make('select', 'ocam_type_filter', __('Type Filter'))
                ->set_options([
                    'category' => 'Text Category',
                    'tag' => 'Text Tag',
                ])
                ->set_default_value('category'),
        ]);
});
composer require htmlburger/carbon-fields

Composer 說明

這段程式必需要在上傳外掛的目錄上執行。要事先安裝 carbon-fields library 才可啟用外掛。因為程式的欄位建立都是靠這個 library 。

結果畫面

Wordpress 外掛 screen shot

要取得參數可用 carbon_get_theme_option 來取得。如

carbon_get_theme_option('ocam_number_range')

這也只是後台畫面骨架。但實際的程式流程你也可自已整合或另開 chatgpt 詢問,之後再自已整合兩邊程式。當然你也可再修改提示詞把你要的功能全部寫好。

Carbon Fields 官網

延伸閱讀

blog.ocam.live
blog.ocam.live

關注科技新聞、SEO、人工智慧、電玩模擬器、程式設言、與 IT 日常等議題,深入簡出文章的說明並持續追蹤相關新聞的發展與報導。