Basic WordPress Plugin Production Tutorial _php example

Source: Internet
Author: User
Tags datetime php code

Plug-in production preparation

First of all, we add a folder in the \wp-content\plugins directory called "My-mood", 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 named format: such as the following code

<!--? php <br?-->
/* Plugin name:my Mood Plugin uri:http://www.aips.me Description
: a mood release plugin
version:1.0
Author: Zhou Liang blog
Author uri:http://www.aips.me
LICENSE:GPL
* *?>


    • The name of the Plugin name represents the plugin.
    • The Plugin URI represents the posting address of the plug-in.
    • Description represents a description of the plugin.
    • Version is good, the first version uses 1.0, and if your plugin is updated, change the version parameter in turn.
    • Author represents the name of the plugin author.
    • The Author URI represents the author's home page.
    • License represents the plug-in License, if you are open source on the use of the GPL, about License parameters can be Baidu or Google inquiries, there is no longer too much space to describe.

Initialization installation of Plug-ins

The plug-in is not just a change in style, usually we will add a new table, then the new table I am through the plug-in installation function to complete, we continue to add the following code in the index.php:

<!--? php <br?-->//Activation action
register_activation_hook (__file__, ' My_mood_install ');

function My_mood_install () {

//enabled What to do
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 ' isn't null,
status int not null,
mood int not NULL,
text text is not NULL, address
varchar DEFAULT ' is not NULL,
UNIQUE KEY ID (ID)
$char Set_collate; ";

Require_once (Abspath. ' wp-admin/includes/upgrade.php ');
Dbdelta ($sql);
>

As the above code comments, we through the Register_activation_hook activation action to complete the plug-in installation, activation action through the parameter My_mood_install, find the function named My_mood_install execution, This action is performed when the plug-in is activated.

We created a table named "Mood" through the My_mood_install function, the database table was created through the WordPress Dbdelta function to execute the SQL statement, in order to use this function need to first introduce wp-admin/includes/ upgrade.php files.

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

Plugin Uninstall

Since WordPress has installed also will certainly have uninstall. The WordPress plug-in uninstall method is through a fixed named file called Uninstall.php to execute, in the plug-in root directory to build a file called uninstall.php, the code is as follows:

<!--? php <br?-->//Uninstall Action
My_mood_uninstall ();

function My_mood_uninstall () {

//executing content
global $wpdb;
$table _name = $wpdb->prefix. "Mood";
$wpdb->query ("DROP TABLE IF EXISTS".) $table _name);
>

Through WordPress $wpdb->query to execute SQL, delete the table we created when we install, so that we delete all the content related to the plugin.

Add a background admin menu to a plugin

As in the following code:

<!--? php <br?-->//Add menu
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 "
);
>

With the above code, we can add a menu to the plugin. method by adding a menu through add_action (' Admin_menu ', ' My_mood_create_menu '), and the menu specific page is bound by parameters, as the above method is passed the parameter called "Test", so when clicking this "my Mood "The menu will look for the method called" test "to do the output of the style, we give the test method

<!--? php <br?--> 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 ");?> <div id=" My-mood ">foreach ($fivesdrafts as $fivesdraft) {?>}?> <tab Le class= "Widefat" > <thead> <tr> <th> release content </th> <th> now in the </th> <th> mood
</th> <th> Creation Date </th> <th> operation </th> </tr> </thead> <tfoot> <tr> <th> content </th> <th> now in </th> <th> mood </th> <th> Date created </th> <th> Operations </th> </tr> </tfoot> <tbody> <tr> <td><input name= "text" type= "text" value= "" Placeholder= "Enter your Mood"/></td> <td><input name= "Address" type= "text" value= "" placeholder= "Enter now location"/ ></td> <td><label> Happy: <input class= "Mood" checked= "checked" NAMe= "Mood" type= "Radio" value= "0"/></label> <label> General: <input class= "Mood" name= "Mood" type= "Radio" Value= "1"/></label> <label> sadness: <input class= "Mood" name= "Mood" type= "Radio" value= "2"/></ Label> <label> worry: <input class= "Mood" name= "Mood" type= "Radio" value= "3"/></label> <label>
Others: <input class= "Mood" name= "Mood" type= "Radio" value= "4"/></label></td> <td></td> <td><a class= "Add" > Add </a></td> </tr> <!--? php <br?--> <tr> <td> <input name= "text" type= "text" value= "' <?php"/>text;?> '/></td> <td><input " Address "type=" text "value=" ' <?php '/>address;?> '/></td> <td><label> happy: <input class= "Mood" name= "mood<?php echo $fivesdraft->id;?>" type= "Radio"/>mood==0? Checked=checked ': '?> value= "0" ></label> <label> General: <input class= "Mood" name= "mood<"? php echo $fivesdraft->id;?> "type=" Radio "/>mood== ' 1 '?" Checked=checked ': '?> value= "1" ></label> <label> sadness: <input class= "Mood" name= "mood<?php" echo $fivesdraft->id;?> "type=" Radio "/>mood==2?" Checked=checked ': '?> value= "2" ></label> <label> worry: <input class= "Mood" name= "mood<?php" echo $fivesdraft->id;?> "type=" Radio "/>mood==3?" Checked=checked ': ';?> value= "3" ></label> <label> Other: <input class= "Mood" name= "mood<?php" echo $fivesdraft->id;?> "type=" Radio "/>mood==4?" Checked=checked ': ';?> value= "4" ></label></td> <td></td> <td><a class= "edit "> Save </a><a class=" Delete "> Delete </a></td> </tr> <!--? php <br?--></tbody

 > </table> </div> <!--? php <br?-->}?>

The test method is a mix of PHP and HTML code, where the HTML part is primarily responsible for the output of the style, while the PHP code is responsible for executing the logic of fetching data. Mainly from the database to read the part, through the WordPress $wpdb->get_results method can be taken from the database in the first step we created the data in the table, returned a data collection, contains more than one data. Finally, the data is exported through a foreach loop.

We show the data interface, so how can we save the data? Also according to the previous mood plug-in example, first look at the following code

<!--? php <br?--> function aad_load_scripts ($hook) {
global $my _settings;
if ($hook!= $my _settings) return
;
/* Load Ajax JS file, can also load other JavaScript and/or CSS and so on * *
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 ');
/* Create validation nonce
it will output similar to:
<![ cdata[
var aad_vars = {"Aad_nonce": "5c18514d34"};
] >
is commented out of JS to HTML.
* *
wp_localize_script (' My-js ', ' My_vars ', Array (
' my_nonce ' => wp_create_nonce (' aad-nonce ')
)
);
}
Add_action (' admin_enqueue_scripts ', ' aad_load_scripts ');
? >

Where the code for 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 through the hook we need the JS code and CSS code, so that our plug-in JS and CSS will be inserted into the page code because of the plug-in's activation.
We implement asynchronous loading of data according to the following code:

<!--? php <br?--> function Say () {
$return =array ();
$return [' success '] = ' 1 ';
$return [' msg ']=$_post[' value ']. " Test-ajax ";
echo Json_encode ($return);
Die ();
}
Add_action (' Wp_ajax_say ', ' say ');
? >

This code means to use AJAX to submit data, add_action (' wp_ajax_ function name ', functions name) of the format is to register a say route, it corresponds to the 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 the JS code action for say

The same reason data to be added to register a add_mood route

<!--? php <br?--> 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 ');
? >

Data to be deleted, register for a delete_mood route

<!--? php <br?--> 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 ');
? >

Data to be edited and registered for a edit_mood route

<!--? php <br?--> 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 ');
? >

The PHP function corresponding to the above additions and deletions is shown below

<!--? php <br?--> 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)
);
>

<!--? php <br?--> function Delete ($id) {
global $wpdb;

$table _name = $wpdb->prefix. "Mood";
$wpdb->delete (
$table _name,
array (
' id ' => $id
)
}
? >

<!--? php <br?--> 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
)
);
>

Now the plugin's background data and interface have been processed, then how to our mood plug-ins in the foreground reference it? We need to add the following code

<!--? php <br?--> function mood_dispaly () {
global $wpdb;
$table _name = $wpdb->prefix. "Mood";

$fivesdrafts = $wpdb->get_results (
"
select text from
$table _name order by
CreatedOn DESC
LIMIT
"
);

? >

<!--? php <br?-->}
?>

This code to the database stored in the mood data through the HTML display in the foreground, so where to control it? Remember the first step we added JS and CSS, yes, style is the first step through the insertion of the style to control.

To this a complete mood plugin is complete, according to the example you can make a own mood plug-ins.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.