/*

* post meta from 添加文章来源自定义字段

* ====================================================

*/

// 创建字段信息

$postmeta_from=array(

    array(

        "name"=>"fromname",

        "std"=>"",

        "title"=>__('来源名','orui').':'

    ),

    array(

        "name"=>"fromurl",

        "std"=>"",

        "title"=>__('来源网址','orui').':'

    )

);

// 函数连接到指定 action(动作)

add_action('admin_menu','_postmeta_from_create');

add_action('save_post','_postmeta_from_save');

//创建自定义字段输入框

function_postmeta_from(){

    global$post,$postmeta_from;

    foreach($postmeta_from 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>'.$meta_box['title'].'</p>';

        echo'<p><input type="text" style="width:98%" value="'.$meta_box_value.'" name="'.$meta_box['name'].'_value"></p>';

    }

    echo'<input type="hidden" name="post_newmetaboxes_noncename" id="post_newmetaboxes_noncename" value="'.wp_create_nonce(plugin_basename(__FILE__)).'" />';

}

//创建自定义字段模块

function_postmeta_from_create(){

    global$theme_name;

    if(function_exists('add_meta_box')){

        add_meta_box('new-meta-boxes',__('来源','haoui'),'_postmeta_from','post','normal','high');

    }

}

// 保存数据

function_postmeta_from_save($post_id){

    global$postmeta_from;

    if(!wp_verify_nonce($_POST['post_newmetaboxes_noncename'],plugin_basename(__FILE__)))

        return;

    if(!current_user_can('edit_posts',$post_id))

        return;      

    foreach($postmeta_from 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));

    }

}

// 调用函数

functionmo_get_post_from($pid='',$prevtext='来源:'){

    if(!$pid){

        $pid=get_the_ID();

    }

    $fromname=trim(get_post_meta($pid,"fromname_value",true));

    $fromurl=trim(get_post_meta($pid,"fromurl_value",true));

    $from='';

    if($fromname){

        if($fromurl){

            $from='<a href="'.$fromurl.'" target="_blank" rel="external nofollow">'.$fromname.'</a>';

        }else{

            $from=$fromname;

        }

        $from=($prevtext).$from;

    }

    return$from;

}