请帮助我:
我的自定义元数据库未保存!!
#add a metabox
add_action( \'add_meta_boxes\', \'adding_meta_box\' );
function adding_meta_box()
{
add_meta_box( \'meta_box_id\', \'اطلاعات پست\', \'frst_meta_box\', \'page_news_letter\', \'normal\', \'high\' );
}
function frst_meta_box( $post )
{
$value = get_post_custom( $post->ID );
$text_field_one = isset( $value[\'news_one\'] ) ? esc_attr( $value[\'news_one\'][0] ) : \'\';
wp_nonce_field( \'my_meta_box_nonce\', \'meta_box_nonce\' );
?>
<?php
$my_custom_query= new WP_Query(array(
\'post_type\' => \'post\',
\'post_status\' => \'publish\',
\'cat\' => \'1\',
\'order\' => \'DESC\',
\'orderby\' => \'ID\',
\'posts_per_page\' =>\'10\',
\'paged\' => (get_query_var(\'paged\')) ? get_query_var(\'paged\') : 1
)); ?>
<?php
if($my_custom_query->have_posts()) : ?>
<select name="news_one" id="news_one">
<?php while($my_custom_query->have_posts()) : $my_custom_query->the_post();?>
<option value="<?php the_title(); ?>"><?php the_title(); ?></option>
<?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_query(); ?>
</select>
#saving metabox
add_action( \'save_post\', \'saving_meta_box\' );
function saving_meta_box( $post_id )
{
if( defined( \'DOING_AUTOSAVE\' ) && DOING_AUTOSAVE ) return;
if( !isset( $_POST[\'meta_box_nonce\'] ) || !wp_verify_nonce( $_POST[\'meta_box_nonce\'], \'my_meta_box_nonce\' ) ) return;
if( !current_user_can( \'edit_post\' ) ) return;
$accepted_field = array(
\'a\' => array(\'href\' => array() )
);
if( isset( $_POST[\'news_one\'] ) )
update_post_meta( $post_id, \'news_one\', wp_kses( $_POST[\'news_one\'], $accepted_field ) );
最合适的回答,由SO网友:cybmeta 整理而成
您错了,您的自定义字段已保存,但在选择框中看不到预先选定的值。要查看它,您必须设置selected
的属性select
要素您可以轻松地使用selected()
function. 您还应该转义属性值,并在您的情况下使用wp_reset_postdata
而不是wp_reset_query
:
if($my_custom_query->have_posts()) : ?>
<select name="news_one" id="news_one">
<?php while($my_custom_query->have_posts()) :
$my_custom_query->the_post();
$title = get_the_title();
?>
<option value="<?php esc_attr_e($title); ?>" <?php selected( $text_field_one, $title ); ?>><?php echo $title; ?></option>
<?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_postdata(); ?>