我设置了2个新的帖子元字段,以便为自定义帖子类型添加功能。自定义字段通常按预期工作,但有几个例外。我设置了一个复选框(称为“餐厅选项”),这样,如果选中,就会在前端添加一个新选项卡,并显示文本区域字段中的内容(称为“特色菜文本区域”)。
问题是,当我在文本区域中输入信息时,它会保存为自定义字段,但不会保存在文本区域本身,文本区域显示为空白。因此,如果一篇文章被更新,并且没有重新输入该内容,它将被覆盖为空白。
以下是我为插件编写的代码:
/**
* Adds a meta box to the post editing screen
*/
function gwrrest_custom_meta() {
$post_types = array ( \'supplier\' );
foreach( $post_types as $post_type ) {
add_meta_box(
\'gwrrest_meta\',
__( \'Restaurant Options\', \'gwrrest-textdomain\' ),
\'gwrrest_meta_callback\',
$post_type,
\'normal\',
\'high\'
);
}
}
add_action( \'add_meta_boxes\', \'gwrrest_custom_meta\' );
/**
* Outputs the content of the meta box
*/
function gwrrest_meta_callback( $post ) {
wp_nonce_field( basename( __FILE__ ), \'gwrrest_nonce\' );
$gwrrest_stored_meta = get_post_meta( $post->ID );
?>
<?php _e( \'Is this a restaurant? \', \'gwrrest-textdomain\' )?>
</span>
<div class="gwrrest-row-content">
<label for="restaurant-options">
<input type="checkbox" name="restaurant-options" id="restaurant-options" value="yes" <?php if ( isset ( $gwrrest_stored_meta[\'restaurant-options\'] ) ) checked( $gwrrest_stored_meta[\'restaurant-options\'][0], \'yes\' ); ?> />
<?php _e( \'Check to add a specials section to the restaurant pages\', \'gwrrest-textdomain\' )?>
</label>
</div>
</p>
<p>
<label for="specials-textarea" class="prfx-row-title"><?php _e( \'Enter Specials Content Here\', \'prfx-textdomain\' )?></label>
<textarea name="specials-textarea" id="specials-textarea"><?php if ( isset ( $prfx_stored_meta[\'specials-textarea\'] ) ) echo $prfx_stored_meta[\'specials-textarea\'][0]; ?></textarea>
</p>
<?php
}
/**
* Saves the custom meta input
*/
function gwrrest_meta_save( $post_id ) {
// Checks save status
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ \'gwrrest_nonce\' ] ) && wp_verify_nonce( $_POST[ \'gwrrest_nonce\' ], basename( __FILE__ ) ) ) ? \'true\' : \'false\';
// Exits script depending on save status
if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
return;
}
// Checks for input and saves
if ( isset( $_POST[\'restaurant-options\'] ) && $_POST[\'restaurant-options\'] ) {
add_post_meta( $post_id, \'restaurant-options\', \'yes\', true );
} else {
delete_post_meta( $post_id, \'restaurant-options\' );
}
// Checks for input and saves if needed
if( isset( $_POST[ \'specials-textarea\' ] ) ) {
update_post_meta( $post_id, \'specials-textarea\', $_POST[ \'specials-textarea\' ] );
} else {
delete_post_meta( $post_id, \'specials-textarea\' );
}
}
add_action( \'save_post\', \'gwrrest_meta_save\' );
我觉得问题在于我如何设置
update_post_meta
. 我也很想知道如何保持文本区域填充保存的数据。这是一个
screenshot of the backend.