1

help me please:

my custom metabox not save !!

#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 ) );
1

You are wrong, your custom field is saved but you won't see the value pre-selected in the select box. To see it you have to set the selected attribute of the select element. You can do it easily with selected() function. You should also escape the attribute values and, in your case, use wp_reset_postdata instead of 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(); ?>
3
  • tanx my freind :)
    – Ehsan
    Feb 22 '15 at 12:13
  • how i do it????
    – Ehsan
    Feb 24 '15 at 2:50
  • Bellow the up/dow voting buttons, at the top-left of the answer, there is a check mark.
    – cybmeta
    Feb 24 '15 at 8:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.