0

i have this query

add_action('edit_form_after_title', 'get_books');

function get_books($main_post){
    global $post;
    $list = '';

    // print the current post (everything is still fine here)
    print_r($post);

    $args = array(
        'posts_per_page' => '20',
        'post_type'      => array('books')
    );
    $my_query = new WP_Query($args);
    if ($my_query->have_posts()) {
        $list .= '<select name="books_list">';
        while ($my_query->have_posts()) {
            $my_query->the_post();
            // my code
            $list .= '<option value="'.get_the_ID().'">'.get_the_title().'</option>';
        }
        $list .= '</select>';
        wp_reset_postdata();
    }
    // i try another methods but still same problem.
    wp_reset_postdata();
    $my_query->reset_postdata();
    wp_reset_query();


    // here print the last post in $my_query, not old post or empty post in add new post page
    print_r($post);

    echo $list;
}

but after complete the query he print last post in $my_query

my problem not in print_r exactly (only to show simple explain) but my problem on add new post or edit post page, he show featured image and other infomations of my last post in $my_query

i fix this problem by put $post in another variable before my query and restore it to $post after complete, but i want to know what problem with wp_reset_postdata or what misake i'm making.

  • What is this code meant to do if it works correctly? Have you called query_posts anywhere? Are there any modifications to WP itself? – Tom J Nowell Jun 9 at 14:21
  • i want this function to get books list and put in select list and output it after title, see my update, i do not call any query_posts in my code – Boyzen Jun 9 at 14:32

Your Answer

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

Browse other questions tagged or ask your own question.