插件制作准备工作
首先我们在\wp-content\plugins目录下添加一个文件夹叫做”My-Mood”,在文件夹中添加一个叫做index.php的主文件,这个是插件的主文件,文件的开始需要一些命名的格式:如下面的代码
<!--?php <br ?--> /* Plugin Name: My Mood Plugin URI: http://www.aips.me Description: 一个心情发布插件 Version: 1.0 Author: 周良博客 Author URI: http://www.aips.me License: GPL */ ?>
- Plugin Name 代表了插件的名字。
- Plugin URI 代表的是插件的发布地址。
- Description 代表的是关于这个插件的描述。
- Version 代表了版本好,第一个版本使用1.0,如果你的插件有更新,就依次更改这个版本参数。
- Author 代表插件作者的名字。
- Author URI 代表作者的主页。。
- License 代表了插件的License,如果你是开源的就使用GPL,关于License的参数可以百度或者Google查询,这里不再过多的篇幅叙述。
插件的初始化安装
插件不仅仅是样式的改变,通常我们会加入新的表,那么新加的表我就是通过插件的安装函数来完成的,我们继续在index.php中加入如下的代码:
<!--?php <br ?--> //激活动作 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 ); } ?>
如上面代码的注释,我们通过register_activation_hook激活动作来完成插件的安装,激活动作通过参数my_mood_install,找到名为my_mood_install的函数执行,这个动作会在插件激活的时候执行。
我们通过my_mood_install函数创建了一张名为”mood”的表,数据库表的创建是通过Wordpress的dbDelta函数来执行sql语句完成的,要想使用此函数需要先引入wp-admin/includes/upgrade.php文件。
通过上面的代码我们就运用Wordpress内置的方法创建了一张给mood插件存储数据的表。
插件卸载
既然Wordpress有安装也一定会有卸载。Wordpress插件的卸载方法是通过一个叫做uninstall.php的固定命名文件来执行的,在插件根目录下建一个名叫uninstall.php的文件,代码内容如下所示:
<!--?php <br ?--> //卸载动作 my_mood_uninstall(); function my_mood_uninstall() { // 执行内容 global $wpdb; $table_name = $wpdb->prefix . "mood"; $wpdb->query("DROP TABLE IF EXISTS " . $table_name); } ?>
通过Wordpress的$wpdb->query来执行sql,删除我们安装时的创建的表,这样就删除一切与该插件相关的内容了。
给插件添加后台管理菜单
如下面的代码:
<!--?php <br ?--> //添加菜单 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" ); } ?>
通过上面的代码我们就可以为插件添加一个菜单。方法通过add_action( ‘admin_menu', ‘my_mood_create_menu' )添加一个菜单而菜单具体的页面则是通过参数来绑定的,如上面的方法是传入了叫做”test”的参数,因此当点击这个”My Mood”的菜单的时候就会去寻找叫做”test”的方法进行样式的输出,我们给出test方法
<!--?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 ) { ?> } ?> <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> <!--?php <br ?--> <tr> <td><input name="text" type="text" value="'<?php" />text; ?>'/></td> <td><input name="address" type="text" value="'<?php" />address; ?>'/></td> <td><label>高兴:<input class="mood" name="mood<?php echo $fivesdraft->id; ?>" type="radio" />mood==0?'checked=checked':''; ?> value="0"></label> <label>一般:<input class="mood" name="mood<?php echo $fivesdraft->id; ?>" type="radio" />mood=='1'?'checked=checked':''; ?> value="1"></label> <label>悲伤:<input class="mood" name="mood<?php echo $fivesdraft->id; ?>" type="radio" />mood==2?'checked=checked':''; ?> value="2"></label> <label>忧虑:<input class="mood" name="mood<?php echo $fivesdraft->id; ?>" type="radio" />mood==3?'checked=checked':''; ?> value="3"></label> <label>其他:<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">保存</a><a class="delete">删除</a></td> </tr> <!--?php <br ?--></tbody> </table> </div> <!--?php <br ?--> } ?>
test方法是php与html代码混编的样式,其中HTMl部分主要负责样式的输出,而PHP的代码则是负责执行取数据的逻辑。主要从数据库读取数据的部分,通过Wordpress的$wpdb->get_results方法就可以从数据库中取出我们第一步中创建的表中的数据,返回的是一个数据集合,包含了多条数据。最后通过foreach循环将数据输出。
我们把数据的界面显示出来了,那么怎样才能将数据保存呢?同样根据上一篇心情插件的例子,先看下面的代码
<!--?php <br ?--> 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'); ?>
其中index.js的代码如下
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; } }); }) });
在上面的代码中我们通过Hook插入我们需要js代码和css代码,这样我们插件的js和css就会因为插件的启用而插入到页面代码中。
我们实现异步加载数据,要根据下面的代码:
<!--?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'); ?>
这段代码的意思是要使用ajax提交数据,add_action(‘wp_ajax_函数名',函数名)的格式就是注册一个say路由,它对应的js代码是
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){ } }); })
因此可以看到js代码的action为say
同样的道理数据要进行添加,注册一个add_mood的路由
<!--?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'); ?>
数据要进行删除,注册一个delete_mood的路由
<!--?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'); ?>
数据要进行编辑,注册一个edit_mood的路由
<!--?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'); ?>
对应上面增删改的php函数如下所示
<!--?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 ) ); } ?>
现在插件的后台数据和界面都已经处理完了,那么怎样把我们的心情插件在前台引用呢?我们需要添加下面的代码
<!--?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 10 " ); ?> <!--?php <br ?--> } ?>
这段代码就把数据库中存储的心情数据通过HTML显示在前台,那么样子哪里控制的呢?还记得第一步我们添加的js和css吗,是的,样式就是通过第一步插入的样式来控制的。
到此一个完整的心情插件就完成了,照着例子你就可以制作一个属于自己的心情插件了。

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6
Visual web development tools