在前面我们已经学会如何创建一个插件,并让wordpress识别出来。不清楚的请看WordPress插件制作教程一新建插件一文,今天我们继续学习WordPress插件制作教程第二课,实现插件功能。本文仅以一个简单功能作为例子,在实际应用中,插件的功能实现并不是这么简单。
插件实现的功能是给文章添加一段文章失效提示,具体效果可见本站部分文章的首段。其中实现功能的代码,我也写过教程了,详见WordPress添加文章过时失效提示。
下面是具体代码:
复制
<?php /* Plugin Name: DMD Plugin Plugin URI: https://www.daimadog.org/1111.html Description: 这里是插件的描述内容,自己填写 Author: 代码狗 Version: 1.0 Author URI: https://www.daimadog.org/ Text Domain: daimadog Domain Path: /languages License: GPL2 License URI: https://www.daimadog.org/licenses.html {Plugin Name} is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or any later version. {Plugin Name} is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with {Plugin Name}. If not, see {License URI}. */ //文章过期提示 function article_time_update($content) { date_default_timezone_set('PRC'); $newdate = time(); $updated_date = get_the_modified_time('Y-m-d H:i:s'); $updatetime = strtotime($updated_date); $custom_content = ''; if ($newdate > $updatetime + 86400) { $custom_content = '<div class="article-timeout"><strong>重要:</strong>本文最后更新于<code>' . $updated_date . '</code>,某些文章具有时效性,若有错误或已失效,请在下方<a href="#comment">留言</a>或联系<a target="_blank" title="代码狗博客" href="https://www.daimadog.org/about"><b>代码狗</b></a>。</div >'; } echo $custom_content . $content; } add_action('the_content', 'article_time_update'); ?>
有人可能会问,这段代码不是在functions.php
文件中使用的吗?为什么照搬到插件中仍然有效?
我记得很久以前我就说过,wordpress会将functions.php
与插件文件内容全部加载到一起使用,也就是说你在functions.php
中定义的函数,在插件中也是可以正常使用的哟,大家可以试试。
评论 (2)