Table of Contents
Basic WordPress plug-in production tutorial, wordpress plug-in tutorial
Home Backend Development PHP Tutorial Basic WordPress plug-in production tutorial, wordpress plug-in tutorial_PHP tutorial

Basic WordPress plug-in production tutorial, wordpress plug-in tutorial_PHP tutorial

Jul 12, 2016 am 09:04 AM
wordpress plug-in

Basic WordPress plug-in production tutorial, wordpress plug-in tutorial

Plug-in production preparation work

First we add a folder called "My-Mood" in the wp-contentplugins directory, and add a main file called index.php in the folder. This is the main file of the plug-in. The beginning of the file needs some naming. Format: as below code

<!--&#63;php <br &#63;--> /*
Plugin Name: My Mood
Plugin URI: http://www.aips.me
Description: 一个心情发布插件
Version: 1.0
Author: 周良博客
Author URI: http://www.aips.me
License: GPL
*/
&#63;>

Copy after login
  • Plugin Name represents the name of the plug-in.
  • Plugin URI represents the release address of the plug-in.
  • Description represents the description of this plug-in.
  • Version represents the version. The first version uses 1.0. If your plug-in is updated, change this version parameter in sequence.
  • Author represents the name of the plugin author.
  • Author URI represents the author's homepage. .
  • License represents the license of the plug-in. If you are open source, use GPL. You can query the parameters of the license on Baidu or Google. I will not describe it in too much length here.

Initial installation of plug-in

Plug-ins are not just style changes. Usually we add new tables. Then I complete the newly added tables through the installation function of the plug-in. We continue to add the following code to index.php:

<!--&#63;php <br &#63;--> //激活动作
register_activation_hook( __FILE__, 'my_mood_install');

function my_mood_install() {

// 启用时要做的事情
global $wpdb;

$table_name = $wpdb->prefix . "mood";

$charset_collate = $wpdb->get_charset_collate();

$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
createdon datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
publishedon datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
status int NOT NULL,
mood int NOT NULL,
text text NOT NULL,
address varchar(55) DEFAULT '' NOT NULL,
UNIQUE KEY id (id)
) $charset_collate;";

require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
&#63;>

Copy after login

As commented in the above code, we complete the installation of the plug-in through the register_activation_hook activation action. The activation action is executed through the parameter my_mood_install and the function named my_mood_install is found. This action will be executed when the plug-in is activated.

We created a table named "mood" through the my_mood_install function. The creation of the database table is completed through WordPress's dbDelta function to execute the sql statement. To use this function, you need to introduce wp-admin/includes/ upgrade.php file.

Through the above code, we use the built-in method of WordPress to create a table to store data for the mood plug-in.

Plugin uninstall

Since WordPress is installed, it must be uninstalled. The uninstallation method of the WordPress plug-in is performed through a fixedly named file called uninstall.php. Create a file named uninstall.php in the root directory of the plug-in. The code content is as follows:

<!--&#63;php <br &#63;--> //卸载动作
my_mood_uninstall();

function my_mood_uninstall() {

// 执行内容
global $wpdb;
$table_name = $wpdb->prefix . "mood";
$wpdb->query("DROP TABLE IF EXISTS " . $table_name);
}
&#63;>

Copy after login

Execute sql through $wpdb->query of Wordpress and delete the table created during our installation. This will delete all content related to the plug-in.

Add background management menu to the plug-in

Such as the following code:

<!--&#63;php <br &#63;--> //添加菜单
add_action( 'admin_menu', 'my_mood_create_menu' );
function my_mood_create_menu() {
global $my_settings;
$my_mood_settings=add_menu_page(
"My Mood",
"My Mood",
"manage_options",
"my-mood",
"test"
);
}
&#63;>
Copy after login

With the above code we can add a menu to the plug-in. The method adds a menu through add_action('admin_menu', 'my_mood_create_menu') and the specific page of the menu is bound through parameters. For example, the above method passes in a parameter called "test", so when clicking this "My Mood" menu, you will look for a method called "test" to output the style. We give the test method

<!--&#63;php <br &#63;--> function test(){
global $wpdb;
$table_name = $wpdb->prefix . "mood";

$fivesdrafts = $wpdb->get_results(
"
SELECT id, createdon, publishedon,status,mood,text,address
FROM $table_name
ORDER BY createdon DESC
"
);
&#63;>
<div id="my-mood">foreach ( $fivesdrafts as $fivesdraft )
{
&#63;> }
&#63;>
<table class="widefat">
<thead>
<tr>
<th>发布内容</th>
<th>现在所在的</th>
<th>心情</th>
<th>创建日期</th>
<th>操作</th>
</tr>
</thead>
<tfoot>
<tr>
<th>发布内容</th>
<th>现在所在的</th>
<th>心情</th>
<th>创建日期</th>
<th>操作</th>
</tr>
</tfoot>
<tbody>
<tr>
<td><input name="text" type="text" value="" placeholder="输入你的心情" /></td>
<td><input name="address" type="text" value="" placeholder="输入现在所在地" /></td>
<td><label>高兴:<input class="mood" checked="checked" name="mood" type="radio" value="0" /></label>
<label>一般:<input class="mood" name="mood" type="radio" value="1" /></label>
<label>悲伤:<input class="mood" name="mood" type="radio" value="2" /></label>
<label>忧虑:<input class="mood" name="mood" type="radio" value="3" /></label>
<label>其他:<input class="mood" name="mood" type="radio" value="4" /></label></td>
<td></td>
<td><a class="add">添加</a></td>
</tr>
<!--&#63;php <br &#63;-->
<tr>
<td><input name="text" type="text" value="'<&#63;php" />text; &#63;>'/></td>
<td><input name="address" type="text" value="'<&#63;php" />address; &#63;>'/></td>
<td><label>高兴:<input class="mood" name="mood<&#63;php echo $fivesdraft->id; &#63;>" type="radio" />mood==0&#63;'checked=checked':''; &#63;> value="0"></label>
<label>一般:<input class="mood" name="mood<&#63;php echo $fivesdraft->id; &#63;>" type="radio" />mood=='1'&#63;'checked=checked':''; &#63;> value="1"></label>
<label>悲伤:<input class="mood" name="mood<&#63;php echo $fivesdraft->id; &#63;>" type="radio" />mood==2&#63;'checked=checked':''; &#63;> value="2"></label>
<label>忧虑:<input class="mood" name="mood<&#63;php echo $fivesdraft->id; &#63;>" type="radio" />mood==3&#63;'checked=checked':''; &#63;> value="3"></label>
<label>其他:<input class="mood" name="mood<&#63;php echo $fivesdraft->id; &#63;>" type="radio" />mood==4&#63;'checked=checked':''; &#63;> value="4"></label></td>
<td></td>
<td><a class="edit">保存</a><a class="delete">删除</a></td>
</tr>
<!--&#63;php <br &#63;--></tbody>
</table>
</div>
<!--&#63;php <br &#63;--> }
&#63;>

Copy after login

The test method is a mixed style of PHP and HTML codes. The HTMl part is mainly responsible for the output of the style, while the PHP code is responsible for executing the logic of fetching data. The main part is to read data from the database. The data in the table we created in the first step can be retrieved from the database through the $wpdb->get_results method of WordPress. What is returned is a data set containing multiple pieces of data. Finally, the data is output through the foreach loop.

We have displayed the data interface, so how can we save the data? Also based on the example of the mood plug-in in the previous article, first look at the following code

<!--&#63;php <br &#63;--> function aad_load_scripts($hook) {
global $my_settings;
if( $hook != $my_settings )
return;
/*载入ajax的js文件,也可以载入其他的javascript和/或css等*/
wp_enqueue_script('my-ajax', plugins_url( 'my-mood/js/index.js', __FILE ), array('jquery'));

wp_register_style( 'my-style', plugins_url( 'my-mood/css/style.css', __FILE ), array(), '', 'all' );
wp_enqueue_style( 'my-style' );

/*
创建验证nonce
它会输出类似于:
<![CDATA[
var aad_vars = {"aad_nonce":"5c18514d34"};
]]>
之类的被注释掉的js到HTML。
*/
wp_localize_script('my-js', 'my_vars', array(
'my_nonce' => wp_create_nonce('aad-nonce')
)
);
}
add_action('admin_enqueue_scripts', 'aad_load_scripts');
&#63;>

Copy after login

The code of index.js is as follows

jQuery(document).ready(function(){
jQuery("input").blur(function(){
var value=jQuery(this).val();
jQuery.ajax({
type:"POST",
url:"/wp-admin/admin-ajax.php",
dataType: 'json',
data:{action:"say",value:value},
success:function(data){
}
});
})

jQuery(".add").click(function(){
var parent=jQuery(this).closest("tr");

var text=jQuery(parent).find("input[name='text']").val();
var address=jQuery(parent).find("input[name='address']").val();
var mood=jQuery(parent).find("input[type='radio']:checked").val();
jQuery.ajax({
type:"POST",
url:"/wp-admin/admin-ajax.php",
dataType: 'json',
data:{action:"add_mood",text:text,address:address,mood:mood},
success:function(data){
window.location.href=window.location;
}
});
})

jQuery(".delete").click(function(){
var parent=jQuery(this).closest("tr");

var id=jQuery(parent).attr('data');
jQuery.ajax({
type:"POST",
url:"/wp-admin/admin-ajax.php",
dataType: 'json',
data:{action:"delete_mood",id:id},
success:function(data){
window.location.href=window.location;
}
});
})

jQuery(".edit").click(function(){
var parent=jQuery(this).closest("tr");

var id=jQuery(parent).attr('data');
var text=jQuery(parent).find("input[name='text']").val();
var address=jQuery(parent).find("input[name='address']").val();
var mood=jQuery(parent).find("input[type='radio']:checked").val();
jQuery.ajax({
type:"POST",
url:"/wp-admin/admin-ajax.php",
dataType: 'json',
data:{action:"edit_mood",id:id,text:text,address:address,mood:mood},
success:function(data){
window.location.href=window.location;
}
});
})

});

Copy after login

In the above code, we insert the js code and css code we need through Hook, so that the js and css of our plug-in will be inserted into the page code because the plug-in is enabled.
We implement asynchronous loading of data according to the following code:

<!--&#63;php <br &#63;--> function say(){
$return=array();
$return['success'] = '1';
$return['msg']=$_POST['value']."test-ajax";
echo json_encode($return);
die();
}
add_action('wp_ajax_say', 'say');
&#63;>
Copy after login

The meaning of this code is to use ajax to submit data. The format of add_action(‘wp_ajax_function name’, function name) is to register a say route, and its corresponding js code is

jQuery("input").blur(function(){
var value=jQuery(this).val();
jQuery.ajax({
type:"POST",
url:"/wp-admin/admin-ajax.php",
dataType: 'json',
data:{action:"say",value:value},
success:function(data){
}
});
})
Copy after login

So you can see that the action of the js code is say

In the same way, data needs to be added, register an add_mood route

<!--&#63;php <br &#63;--> function add_mood(){

$text=$_POST['text'];
$address=$_POST['address'];
$mood=$_POST['mood'];
add($text,$address,$mood);

$return=array();
$return['success'] = '1';
echo json_encode($return);
die();
}
add_action('wp_ajax_add_mood', 'add_mood');
&#63;>

Copy after login

To delete data, register a delete_mood route

<!--&#63;php <br &#63;--> function delete_mood(){

$id=$_POST['id'];
delete($id);

$return=array();
$return['success'] = '1';
echo json_encode($return);
die();
}
add_action('wp_ajax_delete_mood', 'delete_mood');
&#63;>

Copy after login

To edit the data, register an edit_mood route

<!--&#63;php <br &#63;--> function edit_mood(){

$id=$_POST['id'];
$text=$_POST['text'];
$address=$_POST['address'];
$mood=$_POST['mood'];
edit($id,$text,$address,$mood);

$return=array();
$return['success'] = '1';
echo json_encode($return);
die();
}
add_action('wp_ajax_edit_mood', 'edit_mood');
&#63;>

Copy after login

The php functions corresponding to the above additions, deletions and modifications are as follows

<!--&#63;php <br &#63;--> function add($text,$address,$mood){
global $wpdb;

$table_name = $wpdb->prefix . "mood";
$wpdb->insert(
$table_name,
array(
'createdon' => current_time( 'mysql' ),
'publishedon' => current_time( 'mysql' ),
'status' => 1,
'mood' => $mood,
'text'=>$text,
'address'=>$address,
)
);
}
&#63;>

<!--&#63;php <br &#63;--> function delete($id){
global $wpdb;

$table_name = $wpdb->prefix . "mood";
$wpdb->delete(
$table_name,
array(
'id'=>$id
)
);
}
&#63;>

<!--&#63;php <br &#63;--> function edit($id,$text,$address,$mood){
global $wpdb;

$table_name = $wpdb->prefix . "mood";
$wpdb->update(
$table_name,
array(
'mood' => $mood,
'text'=>$text,
'address'=>$address,
),
array(
'id' => $id
)
);
}
&#63;>

Copy after login

Now that the background data and interface of the plug-in have been processed, how do we reference our mood plug-in in the foreground? We need to add the following code

<!--&#63;php <br &#63;--> function mood_dispaly(){
global $wpdb;
$table_name = $wpdb->prefix . "mood";

$fivesdrafts = $wpdb->get_results(
"
SELECT text
FROM $table_name
ORDER BY createdon DESC
LIMIT 10
"
);

&#63;>

<!--&#63;php <br &#63;--> }
&#63;>

Copy after login

This code displays the mood data stored in the database in the foreground through HTML. So where is the appearance controlled? Remember the js and css we added in the first step? Yes, the style is controlled by the style inserted in the first step.

This completes a complete mood plug-in. Following the example, you can create your own mood plug-in.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1075077.htmlTechArticleBasic WordPress plug-in production tutorial, wordpress plug-in tutorial plug-in production preparation work First, we add a wp-contentplugins directory The folder is called "My-Mood", in the folder...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
How to adjust the wordpress article list How to adjust the wordpress article list Apr 20, 2025 am 10:48 AM

There are four ways to adjust the WordPress article list: use theme options, use plugins (such as Post Types Order, WP Post List, Boxy Stuff), use code (add settings in the functions.php file), or modify the WordPress database directly.

How to build a website for wordpress host How to build a website for wordpress host Apr 20, 2025 am 11:12 AM

To build a website using WordPress hosting, you need to: select a reliable hosting provider. Buy a domain name. Set up a WordPress hosting account. Select a topic. Add pages and articles. Install the plug-in. Customize your website. Publish your website.

How to change the head image of the wordpress theme How to change the head image of the wordpress theme Apr 20, 2025 am 10:00 AM

A step-by-step guide to replacing a header image of WordPress: Log in to the WordPress dashboard and navigate to Appearance &gt;Theme. Select the topic you want to edit and click Customize. Open the Theme Options panel and look for the Site Header or Header Image options. Click the Select Image button and upload a new head image. Crop the image and click Save and Crop. Click the Save and Publish button to update the changes.

How to import the source code of wordpress How to import the source code of wordpress Apr 20, 2025 am 11:24 AM

Importing WordPress source code requires the following steps: Create a sub-theme for theme modification. Import the source code and overwrite the files in the sub-topic. Activate the sub-theme to make it effective. Test the changes to make sure everything works.

How to view the front-end of WordPress How to view the front-end of WordPress Apr 20, 2025 am 10:30 AM

You can view the WordPress front-end by logging into the dashboard and switching to the View Sites tab; automate the viewing process with a headless browser; installing the WordPress plugin to preview the front-end within the dashboard; viewing the front-end via a local URL (if WordPress is set locally).

What are the plugins for wordpress blocking ip What are the plugins for wordpress blocking ip Apr 20, 2025 am 08:27 AM

WordPress IP blocking plugin selection is crucial. The following types can be considered: based on .htaccess: efficient, but complex operation; database operation: flexible, but low efficiency; firewall: high security performance, but complex configuration; self-written: highest control, but requires more technical level.

How to cancel the editing date of wordpress How to cancel the editing date of wordpress Apr 20, 2025 am 10:54 AM

WordPress editing dates can be canceled in three ways: 1. Install the Enable Post Date Disable plug-in; 2. Add code in the functions.php file; 3. Manually edit the post_modified column in the wp_posts table.

How to register a wordpress account How to register a wordpress account Apr 20, 2025 am 11:45 AM

To create an account on WordPress, simply visit its website, select the registration option, fill in the registration form, and verify your email address. Other ways to register include using a Google account or Apple ID. The benefits of signing up include creating a website, gaining features, joining the community, and gaining support.

See all articles