โครงสร้าง โฟลเดอร์ Plugin WordPress
/ plugin-name plugin-name.php uninstall.php / languages / includes / admin / js / css / images / public / js / css / images
/ plugin-name plugin-name.php uninstall.php / languages / includes / admin / js / css / images / public / js / css / images
ในการถอนปลั๊กอินจะต้องลบออกให้หมดทุกอย่าง
register_uninstall_hook(__FILE__, ‘pluginprefix_function_to_run’);
// if uninstall.php is not called by WordPress, die if (!defined('WP_UNINSTALL_PLUGIN')) { die; } $option_name = 'wporg_option'; delete_option($option_name); // for site options in Multisite delete_site_option($option_name); // drop a custom database table global $wpdb; $wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}mytable");
การเปิดใช้งาน
register_activation_hook( __FILE__, ‘pluginprefix_function_to_run’ );
ตัวอย่าง
/** * Register the "book" custom post type */ function pluginprefix_setup_post_type() { register_post_type( 'book', ['public' => true ] ); } add_action( 'init', 'pluginprefix_setup_post_type' ); /** * Activate the plugin. */ function pluginprefix_activate() { // Trigger our function that registers the custom post type plugin. pluginprefix_setup_post_type(); // Clear the permalinks after the post type has been registered. flush_rewrite_rules(); } register_activation_hook( __FILE__, 'pluginprefix_activate' );
การปิดใช้งาน
register_deactivation_hook( __FILE__, ‘pluginprefix_function_to_run’ );
/**
* Plugin Name: My Basics Plugin
* Plugin URI: https://example.com/plugins/the-basics/
* Description: Handle the basics with this plugin.
* Version: 1.10.3
* Requires at least: 5.2
* Requires PHP: 7.2
* Author: John Smith
* Author URI: https://author.example.com/
* License: GPL v2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: my-basics-plugin
* Domain Path: /languages
*/
ให้ wordpress ได้สร้างคลาสในการเชื่อมต่อ database ใว้ให้แล้ว https://developer.wordpress.org/reference/classes/wpdb/
ตัวแปรนี้จะประกาศใวใน wp-content/db.php
วิธีใช้งาน ต้องประกาศ global $wpdb; ก่อนใช้งานเสมอ
<?php // 1st Method - Declaring $wpdb as global and using it to execute an SQL query statement that returns a PHP object global $wpdb; $results = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}options WHERE option_id = 1", OBJECT ); ?>
หรือแบบสั้น
<?php // 2nd Method - Utilizing the $GLOBALS superglobal. Does not require global keyword ( but may not be best practice ) $results = $GLOBALS['wpdb']->get_results( "SELECT * FROM {$wpdb->prefix}options WHERE option_id = 1", OBJECT ); ?>