我创建了一个元框。代码是:
// Create your custom meta box
add_action( 'add_meta_boxes', 'hotel_amenities' );
// Add a custom meta box to a post
function hotel_amenities( $post ) {
add_meta_box(
'Meta Box Amenities', // ID, should be a string
'Amenities', // Meta Box Title
'amenities_content', // Your call back function, this is where your form field will go
'post', // The post type you want this to show up on, can be post, page, or custom post type
'normal', // The placement of your meta box, can be normal or side
'high' // The priority in which this will be displayed
);
}
// Content for the custom meta box
function amenities_content( $post ) {
echo '<label>Bed room</label>';
echo '<input type="text" name="amenity_bed_room" value="" />';
}
// Save your meta box content
add_action( 'save_post', 'save_amenities' );
// save newsletter content
function save_amenities(){
global $post;
// Get our form field
if( $_POST ) :
$amenities_meta = esc_attr( $_POST['amenity_bed_room'] );
// Update post meta
update_post_meta($post->ID, '_amenities_custom_meta', $amenities_meta);
endif;
}
它在管理员帖子页面上显示了一个带有文本字段的元框。但是如果我在文本字段中添加了一些内容后保存或更新帖子,它就会变成空白。
似乎function save_amenities()
无效。我在这段代码中做错了什么?
另外,为了获得该值,我使用下面的函数。这是对的吗?
//get amenities meta box values
function get_amenities_meta_box() {
global $post;
$meta_values = get_post_meta($post->ID, '_amenities_custom_meta', true);
}
答案 0 :(得分:4)
那里有一些问题。您希望查看的最终值将由amenities_content
函数中的value属性显示。现在它只显示一个空字符串(&#34;&#34;)。尝试在该属性中添加任何值,您应该会在元框(value="this is a test"
)中看到它。
save_amenities
函数应以$post_id
作为参数。您需要更新帖子元数据并为amenities_content
函数提供真实值以回显管理屏幕。
amenities_content
函数应该有一个nonce字段,然后由save_amenities
函数验证。并且用户输入应该在保存之前进行消毒(我在保存和显示时都这样做。我不确定是否有必要。)
尝试amenities_content
函数:
function amenities_content( $post ) {
// This is the value that was saved in the save_amenities function
$bed_room = get_post_meta( $post->ID, '_amenity_bed_room', true );
wp_nonce_field( 'save_amenity', 'amenity_nonce' );
echo '<label>Bed room</label>';
echo '<input type="text" name="amenity_bed_room"
value="' . sanitize_text_field( $bed_room ) . '" />';
}
这适用于save_amenities
函数:
function save_amenities( $post_id ) {
// Check if nonce is set
if ( ! isset( $_POST['amenity_nonce'] ) ) {
return $post_id;
}
if ( ! wp_verify_nonce( $_POST['amenity_nonce'], 'save_amenity' ) ) {
return $post_id;
}
// Check that the logged in user has permission to edit this post
if ( ! current_user_can( 'edit_post' ) ) {
return $post_id;
}
$bed_room = sanitize_text_field( $_POST['amenity_bed_room'] );
update_post_meta( $post_id, '_amenity_bed_room', $bed_room );
}