[英]Wordpress: Saving post metadata entry in the admin post panel
我正在開發一個插件,在其中定義了一個鈎子,該鈎子應該在管理面板中創建自定義帖子字段。 相同的代碼:
//ADDING CUSTOM FIELDS IN ADMIN PANEL
add_action('add_meta_boxes', 'jericho_meta');
add_action('save_post', 'jericho_saved');
function jericho_meta()
{
add_meta_box('jericho_name', 'Favorite PPV', 'jericho_handler', 'post');
}
function jericho_handler()
{
$value = get_post_custom($post->ID);
$namey = esc_attr($value['jericho_name'][0]);
echo '<label for = "jericho_name">Favorite PPV</label><input type = "text" id = "jericho_name" name = "jericho_name" value = "'.$namey.'" />';
}
function jericho_saved()
{
if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
{
return;
}
if(!current_user_can('edit_post'))
{
return;
}
if(isset($_POST['jericho_name']))
{
update_post_meta($post_id, 'jericho_name', $_POST['jericho_name']);
}
}
此代碼在管理發布面板中生成一個自定義發布字段,如以下屏幕截圖所示:
但是,當我在該文本字段中輸入一個值並單擊Update
,當我嘗試在刷新頁面時檢查該字段時,輸入值永遠不會保存在文本字段中。
我的代碼似乎有什么問題?
編輯1:
我已經更新了代碼,並添加了一個名為save_post
的新操作並定義了其相應功能。 但是,問題似乎出在我定義輸入字段本身的方式上,因為當我嘗試檢查文本字段的元素時,這就是我得到的:
<input type="text" id="jericho_name" name="jericho_name" value>
根據您提供的代碼,我可以看到您沒有注冊用於保存帖子元數據的回調/觸發器。
您需要自己處理(不會自動處理)。 當前,您所做的是在發布后期編輯頁面時綁定了“ jericho_handler()”函數來呈現數據。 這樣就可以正常工作了。
您需要添加其他功能,該功能將在“ save_post”上觸發,在該處您將數據保存到數據庫中。
add_action( 'save_post', 'cd_meta_box_save' );
function cd_meta_box_save( $post_id )
{
// Bail if we're doing an auto save
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
// if our nonce isn't there, or we can't verify it, bail
if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'my_meta_box_nonce' ) ) return;
// if our current user can't edit this post, bail
if( !current_user_can( 'edit_post' ) ) return;
// now we can actually save the data
$allowed = array(
'a' => array( // on allow a tags
'href' => array() // and those anchors can only have href attribute
)
);
// Make sure your data is set before trying to save it
if( isset( $_POST['my_meta_box_text'] ) )
update_post_meta( $post_id, 'my_meta_box_text', wp_kses( $_POST['my_meta_box_text'], $allowed ) );
if( isset( $_POST['my_meta_box_select'] ) )
update_post_meta( $post_id, 'my_meta_box_select', esc_attr( $_POST['my_meta_box_select'] ) );
// This is purely my personal preference for saving check-boxes
$chk = isset( $_POST['my_meta_box_check'] ) && $_POST['my_meta_box_select'] ? 'on' : 'off';
update_post_meta( $post_id, 'my_meta_box_check', $chk );
}
?>
請在此處查看詳細教程。 我上面粘貼的代碼來自此鏈接 。
如果您已經注冊了該處理程序,但仍然遇到問題,請同時使用其他代碼部分更新您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.