Search code examples
phpwordpressmeta-boxes

wp_reset_postdata() doesn't restore the global $post variable


I'm using WP_Query to get posts from a custom post type to use the result in a metabox. Everything works great with my query. But after this query I can't get the other meta values from database.

This is my helper function to get custom field value:

function my_page_get_custom_field( $value ) {
    global $post;

    $custom_field = get_post_meta( $post->ID, $value, true );
    if ( !empty( $custom_field ) )
        return is_array( $custom_field ) ? stripslashes_deep( $custom_field ) : stripslashes( wp_kses_decode_entities( $custom_field ) );

    return false;
}

Here's my query:

$sliderArgs = array(
    'posts_per_page'    => -1,
    'post_type'         => 'slider',
);
$slider = new WP_Query($sliderArgs);
if ($slider->have_posts()) {
?>
    <select name="slider" id="slider">
    $selectedSlide = my_page_get_custom_field('slider');
    while($slider->have_posts()){
        $slider->the_post();
        $slideID = get_the_ID();
        ?><option value="<?php echo $slideID; ?>" <?php selected($selectedSlide, $slideID, true); ?>><?php the_title(); ?></option><?php
    }
    wp_reset_postdata(); ?>
    </select>
}

And this is my other custom field which returns empty (there is a value in database and when I try to change it works great but not displaying in input value in admin):

<input type="text" name="meta_title" id="meta_title" value="<?php echo my_page_get_custom_field('meta_title'); ?>">

Solution

  • OK I solved it.

    I used get_posts instead of WP_Query. This helped me a lot: https://core.trac.wordpress.org/ticket/18408#comment:5