发布时间:2020-09-17
自己动手写 WordPress 插件 3:使用 API,
上两篇讲解了如河,今天我们来点高级点, 🙂 如何使用 WordPress API 进行编写插件。其实我们在前面窗体化 WordPress 插件中已经部分涉及到这方面的知识。只是没有做详细的说明,所以认真看今天的内容也会对你以前的内容也会有所帮助。当然有什么问题,欢迎给我留言。
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script>
首先,什么是 WordPress 的 API?
在很早之前,我们需要添加一些新的功能,需要修改 WordPress 源代码,这是非常的郁闷,而现在有了 API (应用程序接口)之后,我们就能非常容易的添加和修改一些内置的功能。
WordPress 提供两种类型的 API:
关于 WordPress API 更多介绍请参考官方文档:。下面我们来讲解一个实际的例子:根据 Action API 调整性能之后沙发四代。
首先,我们再重复一下 sofa 这个插件的基本逻辑:
假设一个含有500篇日志的博客,一共有80%的日志含有留言,这样
第一步,将进行 1 次 SQL 查询。
第二步,将进行 500X80%=400 次 SQL 查询。
第三步,经进行 3 次 SQL 查询。
这样一个插件是非常耗费资源的。而对一个博客来说,留言数和浏览数数相比,是非常小的一个数据。所以我们是否可以把留言最多的人存到一个数据库中,当有人留言的时候,我们再对其进行更新呢?
答案是肯定,仔细在官方文档的 中找到 comment_post
这个 Action Hook。它是在留言保存到数据库之后进行的行为,这个正是我们所要的。于是我们对 Sofa 插件修改如下:
首先把原有的 get_sofa
函数修改为 update_sofa
,并且把原来得输出沙发党前三名的循环改成获取前三名的数据存入数据中:
$sofa = array(); //初始化写入数据库的沙发数组
for($i=0; $i<3; $i++){
$title="";
if($i==0) $title = "状元:";
if($i==1) $title = "榜眼:";
if($i==2) $title = "探花:";
$q = "SELECT comment_author_url FROM $wpdb->comments WHERE comment_type ='' AND user_id = 0 AND comment_approved = '1' AND comment_author_url !='' AND comment_author = '$first_commentors_author[$i]' limit 1";
$first_comment_url = $wpdb->get_results($q); //获取沙发党的博客
if($first_comment_url){
$sofa[$i] = $title . '<a href="' . $first_comment_url[0] -> comment_author_url . '" title="' . $first_commentors_author[$i].'">' . $first_commentors_author[$i] . '</a>(' . $first_commentors["$first_commentors_author[$i]"].')';
} else {
$sofa[$i] = $title . $first_commentors_author[$i] . '('.$first_commentors["$first_commentors_author[$i]"] . ')';
}
}
update_option('sofa',$sofa);//把沙发排名数据更新到数据库中
然后重新创建一个 get_sofa
函数,这个函数这个时候是从数据库中获取沙发排名数据,然后输出。函数如下:
function get_sofa(){
$output = ""; //初始化输出字符串
$output .= '
<ul class="wp_sofa">';
$sofa = get_option('sofa');
//从数据库中获取沙发排名数据
if(!$sofa[0]){
//如果是第一次使用,把沙发排名数据写入数据库
update_sofa();
$sofa = get_option('sofa');
//重新获取
}
for($i=0; $i<count($sofa); $i++){
$output .= '
<li>'. $sofa[$i] .'</li>
';
}
$output .= '</ul>
';
return $output;//输出沙发党前三甲
}
最后是这个篇教程的关键,当有人留言之后,更新沙发排名信息。函数很简单:
function sofa_comment_post ($comment_ID) {
global $user_ID;
if ( !$user_ID ){
update_sofa();
}
}
add_action('comment_post', 'sofa_comment_post');
关键在于 add_action(‘comment_post‘, ‘sofa_comment_post‘);
它是在用户留言成功之后执行 sofa_comment_post
这个函数,从而更新沙发排名数据到数据库中。
这篇到此为止,这篇完成的插件:,相信性能方面会有非常大的提升,本人会对自己以前开发的插件,会按照同样的方法或者下一章的方法进行更新,如果你是用我开发的插件,请注意关注本博客,注意更新。下一篇将会介绍另外一种更新沙发排名信息的方法,通过 特性来实现定时更新。如果你有什么问题请给我留言。
专题::
本站推荐使用的主机:,国外主机建议使用。
全站搜索