wordpress添加自定义模块
wordpress在发布文章的时候添加自定义模块面板,方便填写自定义字段信息!
代码如下:
$new_meta_boxes =
array(
"huanjing" => array(
"name" => "huanjing",
"std" => "",
"title" => "运行环境:"),
"zuozhe" => array(
"name" => "zuozhe",
"std" => "",
"title" => "软件作者:"),
"yanshi" => array(
"name" => "yanshi",
"std" => "",
"title" => "软件演示:"),
"down" => array(
"name" => "down",
"std" => "",
"title" => "软件下载:"),
"img" => array(
"name" => "img",
"std" => "",
"title" => "软件截图:")
);
function new_meta_boxes() {
global $post, $new_meta_boxes;
foreach($new_meta_boxes as $meta_box) {
$meta_box_value = get_post_meta($post->ID, $meta_box['name'].'_value', true);
if($meta_box_value == "")
$meta_box_value = $meta_box['std'];
// 自定义字段标题
// echo'<h4>'.$meta_box['title'].'</h4>';
// 自定义字段输入框
echo $meta_box['title'].'<input style="width:600px" name="'.$meta_box['name'].'_value" value='.$meta_box_value.'><br />';
}
echo '<input type="hidden" name="newmetaboxes_noncename" id="newmetaboxes_noncename" value="'.wp_create_nonce( plugin_basename(__FILE__) ).'" />';
}
function create_meta_box() {
global $theme_name;
if ( function_exists('add_meta_box') ) {
add_meta_box( 'new-meta-boxes', '软件信息', 'new_meta_boxes', 'post', 'normal', 'high' );
}
}
function save_postdata( $post_id ) {
global $new_meta_boxes;
if ( !wp_verify_nonce( $_POST['newmetaboxes_noncename'], plugin_basename(__FILE__) ))
return;
if ( !current_user_can( 'edit_posts', $post_id ))
return;
foreach($new_meta_boxes as $meta_box) {
$data = $_POST[$meta_box['name'].'_value'];
if(get_post_meta($post_id, $meta_box['name'].'_value') == "")
add_post_meta($post_id, $meta_box['name'].'_value', $data, true);
elseif($data != get_post_meta($post_id, $meta_box['name'].'_value', true))
update_post_meta($post_id, $meta_box['name'].'_value', $data);
elseif($data == "")
delete_post_meta($post_id, $meta_box['name'].'_value', get_post_meta($post_id, $meta_box['name'].'_value', true));
}
}
add_action('admin_menu', 'create_meta_box');
add_action('save_post', 'save_postdata');
插入到functions.php文件的适当位置!