在上一篇文章中WORDPRESS插件開發(一)HELLO WORLD,演示了Hello World的最簡單實現,只是在每篇文章的後面加入Hello World字符,而且字符也是寫死的。
如果用戶需要自己輸入一些文字,然後在每篇文章的後面顯示,改怎麼做呢?
首先要在後臺有一個菜單,點擊菜單顯示一個頁面,在頁面中有一個輸入框,用戶輸入完畢後點擊保存,將內容保存到數據庫,顯示每篇文章時,提取保存的信息到頁面中就可以了。
實現思路
激活插件時,使用add_option函數向wp_options添加一個字段,禁止插件時,使用delete_option函數刪除。
在wordpress後臺設置菜單添加插件菜單,添加菜單時使用add_options_page函數
點擊菜單時,顯示頁面,頁面中一個輸入框一個提交按鈕。
代碼實現
<?php
/*
Plugin Name: Hello-World
Plugin URI: http://1100w.com/
Description: 最簡單的插件實現,在每篇文章的後面追加hello world
Version: 1.0
Author: 1100w
Author URI: http://1100w.com
License: GPL
*/
add_filter('the_content','hello_world');
/* Runs when plugin is activated */
register_activation_hook(__FILE__,'hello_world_install');
/* Runs on plugin deactivation*/
register_deactivation_hook( __FILE__, 'hello_world_remove' );
function hello_world_install() {
add_option("hello_world_data", 'Default', '', 'yes');
}
function hello_world_remove() {
delete_option('hello_world_data');
}
if ( is_admin() ){
/* Call the html code */
add_action('admin_menu', 'hello_world_admin_menu');
function hello_world_admin_menu() {
add_options_page('Hello World', 'Hello World', 'administrator','hello-world', 'hello_world_html_page');
}
}
?>
<?php
function hello_world_html_page() {
?>
<div>
<h2>Hello World Options</h2>
<form method="post" action="options.php">
<?php wp_nonce_field('update-options'); ?>
<table width="510">
<tr valign="top">
<th width="92" scope="row">輸入顯示內容</th>
<td width="406">
<input name="hello_world_data" type="text" id="hello_world_data"
value="<?php echo get_option('hello_world_data'); ?>" />
(ex. Hello World)</td>
</tr>
</table>
<input type="hidden" name="action" value="update" />
<input type="hidden" name="page_options" value="hello_world_data" />
<p>
<input type="submit" value="<?php _e('Save Changes') ?>" />
</p>
</form>
</div>
<?php
}
?>
<?php
//Callback function
function hello_world($content)
{
//Checking if on post page.
if ( is_single() ) {
return $content . '<h1>'.get_option('hello_world_data').'</h1>';
}
else {
return $content;
}
}
?>