Basic WordPress plugin creation tutorial

Source: Internet
Author: User
This article mainly introduces the basic WordPress plug-in creation tutorial, including the implementation of using ajax to submit data. For more information, see Prepare the plug-in

First, add a folder named "My-Mood" under the \ wp-content \ plugins directory and add an index in the folder. the main file of php. this is the main file of the plug-in. some naming formats are required at the beginning of the File: The following code:

 /* Plugin Name: My MoodPlugin URI: http://www.aips.meDescription: a mood release plug-in Version: 1.0 Author: Zhou Liang blog Author URI: http://www.aips.meLicense: GPL */?>

  • Plugin Name indicates the plug-in Name.
  • Plugin URI represents the publishing address of the plug-in.
  • Description indicates the Description of the plug-in.
  • Version indicates that the Version is good. The first Version uses 1.0. if your plug-in is updated, change the Version parameters in sequence.
  • Author represents the name of the plug-in Author.
  • Author URI represents the Author's homepage ..
  • The License represents the License of the plug-in. if you are an open source, you can use GPL. you can query the parameters of the License by baidu or Google. there is no longer much space to describe it here.

Initialize and install the plugin

The plug-in is not just a style change. we usually add a new table, so the newly added table is completed through the plug-in installation function, and we continue in the index. add the following code to php:

 // Activate the 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 '2017-00-00 00:00:00 'not null, publishedon datetime DEFAULT '2017-00-00 00:00:00' not null, status int Not null, mood int not null, text not null, address varchar (55) DEFAULT ''not null, unique key id (id) $ charset_collate;"; require_once (ABSPATH. 'WP-admin/uplodes/upgrade. php '); dbDelta ($ SQL) ;}?>

As mentioned in the code above, we use the register_activation_hook activation action to install the plug-in. the activation action uses the my_mood_install parameter to find the function named my_mood_install for execution. this action is executed when the plug-in is activated.

We created a table named "mood" through the my_mood_install function, and the database table was created using the dbDelta function of Wordpress to execute SQL statements, to use this function, you must first introduce wp-admin/includes/upgrade. php file.

Using the above code, we created a table for the mood plug-in to store data using the built-in Wordpress method.

Plug-in uninstall

If Wordpress is installed, it must be uninstalled. The Wordpress plug-in can be uninstalled through a fixed name file named uninstall. php. create a file named uninstall. php under the root directory of the plug-in. the code content is as follows:

 // Uninstall action my_mood_uninstall (); function my_mood_uninstall () {// execute content global $ wpdb; $ table_name = $ wpdb-> prefix. "mood"; $ wpdb-> query ("drop table if exists ". $ table_name) ;}?>

Run the SQL statement in Wordpress $ wpdb-> query to delete the table we created during installation. in this way, all plug-in-related content is deleted.

Add a background management menu for the plug-in

The following code:

 // 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 for the plug-in. You can use add_action ('admin _ menu ', 'My _ mood_create_menu') to add a menu. the specific page of the menu is bound by parameters, the above method is passed in the parameter "test". Therefore, when you click this "My Mood" menu, you will find the method "test" to output the style, the test method is provided.

 Function test () {global $ wpdb; $ table_name = $ wpdb-> prefix. "mood"; $ fivesdrafts = $ wpdb-> get_results ("SELECT id, createdon, publishedon, status, mood, text, addressFROM $ table_nameORDER BY createdon DESC");?>

Foreach ($ fivesdrafts as $ fivesdraft) {?> }?>

Release content The current Mood Creation date Operation
Release content The current Mood Creation date Operation
Happy:General:Sorrow:Worries:Others: Add
Text;?> '/> Address;?> '/> Happy:Mood = 0? 'Checked = checked': '';?> Value = "0">General:Mood = '1 '? 'Checked = checked': '';?> Value = "1">Sorrow:Mood = 2? 'Checked = checked': '';?> Value = "2">Worries:Mood = 3? 'Checked = checked': '';?> Value = "3">Others:Mood = 4? 'Checked = checked': '';?> Value = "4"> Save and delete

}?>

The test method is a mix of php and html code. the HTMl part is mainly responsible for style output, while the PHP code is responsible for executing the data retrieval logic. The data is read from the database. you can use the $ wpdb-> get_results method of Wordpress to retrieve the data in the table created in step 1 from the database. the returned data is a data set, contains multiple data entries. Finally, the data is output through a foreach loop.

After we display the data interface, how can we save the data? Based on the previous example of mood plug-in, let's take a look at the following code.

 Function aad_load_scripts ($ hook) $ global $ my_settings; if ($ hook! = $ My_settings) return;/* load ajax js files, or load other javascript and/or css files */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 (), '', 'like '); wp_enqueue_style ('My-style');/* Create and verify nonce. it outputs the following information:var aad_vars = {"aad_nonce":"5c18514d34"};And so on. 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');?>

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 need to insert js code and css code through Hook. in this way, the js and css of our plug-in will be inserted into the page code due to the plug-in enabling.
To load data asynchronously, follow the following code:

  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 indicates that data is submitted using ajax. the format of add_action ('WP _ ajax _ function name', function name) is to register a say route, and the 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){}});})

Therefore, we can see that the js code action is say

Similarly, data needs to be added to register an add_mood route.

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

To delete the data, register a delete_mood route.

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

To edit the data, register an edit_mood route

  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 added, deleted, and modified php functions are as follows:

  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,));}?>
  function delete($id){global $wpdb;$table_name = $wpdb->prefix . "mood";$wpdb->delete($table_name,array('id'=>$id));}?>
  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 that the back-end data and interface of the plug-in have been processed, how can we reference the plug-in our mood on the front-end? We need to add the following code

  function mood_dispaly(){global $wpdb;$table_name = $wpdb->prefix . "mood";$fivesdrafts = $wpdb->get_results("SELECT textFROM $table_nameORDER BY createdon DESCLIMIT 10");?>
  }?>

This code displays the mood data stored in the database in HTML at the front-end. how can this code be controlled? Do you still 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. you can create your own mood plug-in by following the example.

Related Article

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.