wordpress文章自定义字段

functions.php
$new_meta_boxes =
array(
    "add1" => array(
        "name" => "add1",
        "std" => "",
        "title" => "职位:"),

    "add2" => array(
        "name" => "add2",
        "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 '<p><span style="display:inline-block;width:80px">'.$meta_box['title'].'</span><input type="text"  size="32" name="'.$meta_box['name'].'_value" value="'.$meta_box_value.'"/></p>';
    }

    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');

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注