WORDPRESS插件开发(二)HELLO WORLD改进版

在上一篇文章中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;
	 }
}
?>



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章