• Tentang Kami
  • Portofolio
  • Paket Web
  • Tutorial Website
  • GRATISAN
  • Lokasi
  • Artikel
Menu
  • Tentang Kami
  • Portofolio
  • Paket Web
  • Tutorial Website
  • GRATISAN
  • Lokasi
  • Artikel

Cara Membuat Custom Plugin WordPress Sendiri

CategoriesArtikel / tutorial website

Yudith Hentreisa

Juli 22, 2024

0 0

Share this post

Cara Membuat Custom Plugin WordPress Sendiri – Dalam tutorial ini, kita akan mendalami pengembangan Custom Plugin WordPress menggunakan bahasa PHP. Tujuan utamanya adalah memberikan referensi kepada pelajar dan pemula, terutama mereka yang baru mengenal WordPress dan PHP, untuk mempelajari teknik-teknik yang berguna guna meningkatkan pengetahuan dan kemampuan pemrograman mereka. Saya akan menyertakan cuplikan kode sampel dan kode sumber plugin WordPress sampel yang menunjukkan tujuan utama kita dalam tutorial ini.

Apa itu WordPress?

WordPress adalah sistem manajemen konten (CMS) sumber terbuka yang banyak digunakan yang memungkinkan pengguna untuk membuat dan mengelola situs web dan blog. WordPress ditulis dalam bahasa PHP dan menggunakan basis data MySQL atau MariaDB. WordPress telah berkembang dari asalnya sebagai platform blog menjadi CMS yang serbaguna yang digunakan oleh individu, bisnis, dan organisasi untuk berbagai jenis situs web, termasuk blog, portofolio, situs e-commerce, dan situs web perusahaan.

Apa itu Plugin WordPress?

Plugin WordPress adalah komponen perangkat lunak yang memperluas dan meningkatkan fungsi situs web WordPress. Plugin sangat penting dalam membuat WordPress menjadi sistem manajemen konten (CMS) yang fleksibel dan dapat disesuaikan. Plugin memungkinkan pengguna untuk menggabungkan fitur atau kemampuan tertentu ke dalam situs web mereka tanpa memodifikasi kode inti WordPress.

Bagaimana Cara Membuat Custom Plugin WordPress?

Langkah 1

Untuk membuat Custom Plugin WordPress, buat direktori baru di situs web WordPress Anda dalam folder source_code_path>wp-contents>plugins. Kemudian, buat file PHP baru.

Langkah 2

Buka file PHP yang baru Anda buat dengan editor kode pilihan Anda, seperti MS VS Code, Sublime, atau Notepad++.

Langkah 3

Selanjutnya, kita perlu memberikan header informasi Plugin di baris atas file PHP. Header informasi ini ditempatkan dalam tag komentar. Di bawah ini adalah contoh header informasi untuk Plugin WordPress sampel:

<?php
/**
 * Plugin Name: My Custom Plugin Name
 * Plugin URI: URI of your plugin where your docs, updates, or etc located
 * Description: A brief description of yout plugin
 * Version: your plugin version
 * Author: the plugins author name
 * Author URI: the plugins author URI
 * License: license name e.g. GPL2
 */  
?>

Setelah menyelesaikan langkah-langkah ini, Anda akan dapat menemukan Custom Plugin WordPress Anda di Halaman Plugin pada sisi admin WordPress Anda.

Cara Membuat Custom Plugin WordPress Sendiri

Untuk pemahaman yang lebih baik dalam membuat Custom Plugin WordPress, saya telah mengembangkan plugin sederhana yang mencakup fitur CRUD (Create, Read, Update, dan Delete) pada sisi admin. Script plugin yang disediakan juga melibatkan pembuatan tabel database baru.

Berikut adalah script PHP untuk plugin sederhana yang saya buat:

<?php
/**
    * Plugin Name: My First Custom Plugin
    * Plugin URI: https://sample-domain.com
    * Description: Lorem ipsum dolor sit amet consectetur adipisicing elit.
    * Version: 1.0
    * Author: oretnom23
    * Author URI: https://www.sourcecodester.com/user/257130/activity
    * License: GPLv2 or later
    */    
 
if ( ! defined( 'ABSPATH' ) ) {
    die;
}
 
class MyFirstPlugin{
    public $notices = [];
    function __construct()
    {
        add_action( 'admin_menu', [ $this, 'pages' ] );
        add_action( 'admin_enqueue_scripts', [$this, 'bootstrap_scripts'], 10, 1 );
 
        // Process Form
        add_action( 'admin_init', [ $this, 'save_form' ] );
        add_action( 'admin_init', [ $this, 'delete_mfcp' ] );
 
        $this->notices = get_option("mfcp_notices", array());
        // print_r(gettype($this->notices));exit;
        add_action( 'admin_notices', [$this, 'display_notices'] );
    }
 
    function pages(){
        //add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position );
        add_menu_page(__('My First Custom Plugin'), __('Custom Plugin'), 'administrator', 'my-first-custom-plugin-page', [$this, 'my_plugin_list_page'], '', 25); 
        add_submenu_page('my-first-custom-plugin-page', __('Manage Plugin\'s DB'), __('Add New'), 'administrator', 'my-first-custom-plugin-page-form', [$this, 'my_plugin_form_page']); 
    }
 
    function display_notices(){
        // print_r($this->notices);exit;
        if(count($this->notices) > 0){
            foreach($this->notices as $k =>$notice){
                ?>
                <div class="notice notice-<?= $notice['type'] ?> <?= ($notice['dismissible']) ? "is-dismissible" : "" ?>">
                    <?= htmlspecialchars_decode($notice['message']) ?>
                </div>
                <?php
                unset($this->notices[$k]);
            }
        }
        update_option("mfcp_notices", []);
 
    }
    function activate(){
        // Install Plugin's Database
        $this->install_db();
    }
    function deactivate(){
 
    }
    function uninstall(){
    }
 
    /**
        * Enqueue Styles and Scripts
        */
    function bootstrap_scripts($hook){
        // Enqueue Bootstrap CDN CSS and JS only in plugin's page
        if($hook == 'toplevel_page_my-first-custom-plugin-page' || $hook == 'custom-plugin_page_my-first-custom-plugin-page-form'){
            wp_enqueue_style("fontawesome-icon-cdn","https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css",[],"6.1.2", "all");
            wp_enqueue_style("bootstrap-css-cdn","https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css",[],"5.3.2", "all");
 
            wp_enqueue_script("fontawesome-icon-js-cdn","https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/js/all.min.js",[],"6.1.2", "all");
            wp_enqueue_script("bootstrap-js-cdn","https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js",[],"5.3.2", "all");
        }
        // echo $hook;exit;
    }
 
    /**
        * Create Plugin's Database
        */
    function install_db(){
        global $wpdb;
        $table = $wpdb->prefix."mfp_tbl";
        $qry = $wpdb->prepare("SHOW TABLES LIKE %s", $wpdb->esc_like($table));
        if($wpdb->get_var($qry) == $table){
            /**
                * Table Already Exists
                */
 
        }else{
            /**
                * Table Doesn't Exists on the Database
                * - Install Table
                */
            $charset_collate = $wpdb->get_charset_collate();
 
            $sql = "CREATE TABLE IF NOT EXISTS $table  (
                `id` int(30) NOT NULL PRIMARY KEY AUTO_INCREMENT,
                `meta_field` text DEFAULT NULL,
                `meta_value` text DEFAULT NULL,
                `created_at` datetime NOT NULL DEFAULT current_timestamp(),
                `updated_at` datetime DEFAULT NULL ON UPDATE current_timestamp()
            ) $charset_collate;";
            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
            dbDelta($sql);
        }
    }
 
    /**
        * Create Plugin's Form Page
        */
    function my_plugin_form_page(){
        global $wpdb;
        if(isset($_GET['mfcp_id'])){
            $data = $wpdb->get_row(
                $wpdb->prepare("SELECT * FROM `{$wpdb->prefix}mfp_tbl` where `id` = %d", [$_GET['mfcp_id']]),
                ARRAY_A
            );
            extract($data, EXTR_PREFIX_ALL, "mfcp");
        }
        ?>
        <style>
            .card{
                max-width: unset !important;
            }
        </style>
        <div class="container-fluid">
            <div class="card shadow col-lg-5 col-md-8 col-sm-12 col-12 mx-auto p-0">
                <div class="card-header rounded-0">
                    <div class="card-title">Plugin's Sample Form <?= (!empty($mfcp_id ?? "")? " - Updating #{$mfcp_id}" : "") ?></div>
                </div>
                <div class="card-body">
                    <div class="container-fluid">
                        <form action="" id="sample-form" method="POST">
                            <?php wp_nonce_field( "mfcp-sample-form" ); ?>
                            <input type="hidden" name="action" value="save-mfcp-sample-form">
                            <input type="hidden" name="id" value="<?= $mfcp_id ?? "" ?>">
                            <div class="mb-3">
                                <label for="meta_field" class="form-label">Meta Field <small class="text-danger">*</small></label>
                                <input type="text" class="form-control rounded-0" id="meta_field" name="meta_field" value="<?= $_POST['meta_field'] ?? $mfcp_meta_field ?? "" ?>" required="required" autofocus>
                            </div>
                            <div class="mb-3">
                                <label for="meta_value" class="form-label">Meta Value <small class="text-danger">*</small></label>
                                <textarea name="meta_value" id="meta_value" rows="3" class="form-control rounded-0" requried=""><?= $_POST['meta_value'] ?? $mfcp_meta_value ?? "" ?></textarea>
                            </div>
                            <div class="mb-3">
                                <button class="btn btn-primary rounded-0" type="submit">Save</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <?
    }
 
    /**
        * Create Plugin's List Page
        */
 
    function my_plugin_list_page(){
        global $wpdb;
        $data = $wpdb->get_results(
            $wpdb->prepare("
                SELECT * FROM `{$wpdb->prefix}mfp_tbl` order by id ASC
            "),
            ARRAY_A
        );
        ?>
        <style>
            .card{
                max-width: unset !important;
            }
        </style>
        <div class="container-fluid">
            <div class="card shadow col-12 p-0">
                <div class="card-header rounded-0">
                    <div class="card-title">Plugin's Database Data</div>
                </div>
                <div class="card-body">
                    <div class="container-fluid">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover table-bordered">
                                <colgroup>
                                    <col width="20%">
                                    <col width="30%">
                                    <col width="30%">
                                    <col width="20%">
                                </colgroup>
                                <thead>
                                    <tr>
                                        <th class="text-center px-2 py-1 text-light bg-primary">Date Added</th>
                                        <th class="text-center px-2 py-1 text-light bg-primary">Meta Field</th>
                                        <th class="text-center px-2 py-1 text-light bg-primary">Meta Value</th>
                                        <th class="text-center px-2 py-1 text-light bg-primary">Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if(!empty($data)): ?>
                                    <?php foreach($data as $row): ?>
                                        <tr>
                                            <td class="px-2 py-1"><?= date("M d, Y g:i A", strtotime($row['created_at'])) ?></td>
                                            <td class="px-2 py-1"><?= $row['meta_field'] ?></td>
                                            <td class="px-2 py-1"><?= $row['meta_value'] ?></td>
                                            <td class="px-2 py-1">
                                                <div class="input-group d-flex justify-content-center">
                                                    <a href="<?= admin_url("admin.php?page=my-first-custom-plugin-page-form&mfcp_id={$row['id']}") ?>" class="btn btn-sm btn-outline-primary rounded-0" title="Edit"><i class="fa fa-edit"></i></a>
                                                    <a href="<?= admin_url("admin.php?page=my-first-custom-plugin-page-form&action=delete_mfcp&mfcp_id={$row['id']}") ?>" class="btn btn-sm btn-outline-danger rounded-0 delete-mfcp" title="Delete"><i class="fa fa-trash"></i></a>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr>
                                            <th class="text-center px-2 py-1" colspan="4">No Data Found!</th>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <script>
            var delete_mfcp = document.querySelectorAll('.delete-mfcp')
            delete_mfcp.forEach(el=>{
                el.addEventListener('click', function(e){
                    if(confirm(`Are you sure to delete this data?`) === false)
                    e.preventDefault();
                })
            })
        </script>
        <?
    }
 
 
    /**
        * Save Form Data
        */
    function save_form(){
        global $wpdb;
        extract($_POST, EXTR_PREFIX_ALL, "mfcp");
        $resp=[];
        if(
            isset($_POST['action']) &&
            $_POST['action'] == 'save-mfcp-sample-form'
        ){
            if(!wp_verify_nonce( $mfcp__wpnonce, 'mfcp-sample-form')){
                $resp = ["type" => "danger", "message" => "Security Check Failed!"];
            }else{
                $mfcp_meta_field = sanitize_text_field( $mfcp_meta_field );
                $mfcp_meta_value = sanitize_textarea_field( $mfcp_meta_value );
                if(empty($mfcp_id)){
                    $save = $wpdb->insert(
                        "{$wpdb->prefix}mfp_tbl",
                        [
                            "meta_field" => $mfcp_meta_field,
                            "meta_value" => $mfcp_meta_value
                        ],
                        [
                            '%s',
                            '%s'
                        ]
                    );
                }else{
                    $save = $wpdb->update("{$wpdb->prefix}mfp_tbl",
                    [
                        "meta_field" => $mfcp_meta_field,
                        "meta_value" => $mfcp_meta_value
                    ],
                    [
                        "id" => $mfcp_id,
                    ],
                    [
                        '%s',
                        '%s'
                    ],
                    [
                        '%d',
                    ]
                    );
                }
                if($wpdb->last_error){
                    $resp = ["type" => "danger", "message" => $wpdb->last_error];
                }else{
                    $resp = ["type" => "success", "message" => "Data has been saved successfully!"];
                }
            }
 
            $this->notices[] = $resp;
            update_option("mfcp_notices", $this->notices);
            echo "<script>location.replace(`".admin_url("admin.php?page=my-first-custom-plugin-page")."`)</script>";
            exit;
        }
 
    }
 
    /**
        * Delete Data
        */
    function delete_mfcp(){
        global $wpdb;
        if(
            isset($_GET['page']) && 
            $_GET['page'] == 'my-first-custom-plugin-page-form' &&
            isset($_GET['action']) && 
            $_GET['action'] == 'delete_mfcp'&&
            isset($_GET['mfcp_id'])
        ){
            $delete = $wpdb->delete("{$wpdb->prefix}mfp_tbl", [ "id" =>  $_GET['mfcp_id']], ['%d']);
            if($wpdb->last_error){
                $resp = ["type" => "danger", "message" => $wpdb->last_error];
            }else{
                $resp = ["type" => "success", "message" => "Data has been deleted successfully!"];
            }
            $this->notices[] = $resp;
            update_option("mfcp_notices", $this->notices);
            echo "<script>location.replace(document.referrer)</script>";
            exit;
        }
    }
 
}
 
if(class_exists("MyFirstPlugin")){
    $MyFirstPlugin = new MyFirstPlugin();
    register_activation_hook(__FILE__ , array ( $MyFirstPlugin , 'activate' ) );
}

Cuplikan Layar

Jelajahi cuplikan layar di bawah ini, yang menangkap hasil dari Script Custom Plugin WordPress yang disediakan di atas:

Dan selesai! Saya berharap Panduan Custom Plugin WordPress ini bermanfaat untuk kebutuhan Anda dan menjadi sumber daya berharga untuk proyek WordPress Anda saat ini dan di masa mendatang.

Jika anda membutuhkan jasa pembuatan website wordpress custom bisa menghubungi nomor WA 087823179122 atau klik tombol WA di bawah website Kami. Terimakasih teleh membaca artikel Cara Membuat Custom Plugin WordPress Sendiri, Semoga Bermanfaat!

Tags: belejar plugin wordpress, cara membuat plugin wordpress, jasa wordpress, tutorial plugin wordpress

Related Post

JUNI 9, 2026

Biaya Pembuatan Website...

Di tengah persaingan industri konstruksi yang semakin ketat, website telah menjadi salah...

00

JUNI 9, 2026

Biaya Pembuatan Website...

Di era digital tahun 2026, website sekolah bukan lagi sekadar pelengkap, tetapi sudah...

00

JUNI 9, 2026

Biaya Pembuatan Website...

Di tahun 2026, website company profile menjadi salah satu kebutuhan utama bagi perusahaan...

00

JUNI 9, 2026

Berapa Biaya Pembuatan...

Di era digital seperti sekarang, website bukan lagi kebutuhan tambahan, melainkan aset...

00

MEI 31, 2026

Ebook Cuan dari Rumah: Cara...

Ebook Cuan dari Rumah – Ingin memulai bisnis online tetapi masih bingung harus...

00

DESEMBER 27, 2025

Cara Melindungi Data Pribadi...

Cara Melindungi Data Pribadi Agar Tidak Masuk Database Mata Elang – Kasus bocornya...

00

Recent Posts

  • Berapa Biaya Pembuatan Website di Indonesia Tahun 2026?

    Juni 9, 2026
  • Panduan biaya pembuatan website kontraktor 2026

    Biaya Pembuatan Website Kontraktor 2026: Panduan Lengkap untuk Perusahaan Konstruksi

    Juni 9, 2026
  • Biaya pembuatan website sekolah 2026

    Biaya Pembuatan Website Sekolah 2026: Panduan Lengkap untuk SD, SMP, SMA, dan SMK

    Juni 9, 2026
  • Biaya Pembuatan Website Company Profile 2026: Panduan Lengkap untuk Perusahaan dan UMKM

    Juni 9, 2026
  • Ebook Cuan dari Rumah: Cara Menjual Produk Hingga Omzet Miliaran Rupiah

    Ebook Cuan dari Rumah: Cara Menjual Produk Hingga Omzet Miliaran Rupiah

    Mei 31, 2026
COPYRIGHT © 2025 | CREATED BY YUDITH / SUNDAKREATIF.COM