search
HomeBackend DevelopmentPHP TutorialBasic WordPress plug-in production tutorial, wordpress plug-in tutorial_PHP tutorial

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;>

  • 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;>

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;>

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;>

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;>

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;>

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;
}
});
})

});

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;>

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){
}
});
})

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;>

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;>

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;>

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;>

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;>

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
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

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

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools