1

I've written a function that grabs all posts that are drafts and puts them as a dropdown in my toolbar for easy access to complete. This works just fine.

The problem is that it seems to mess with my global $post object, specifically when called in my post/page editor.

So if I'm in my post editor: http://example.com/wp-admin/post.php?post=147&action=edit

147 is the post I want to edit. But instead of showing the post corresponding to 147, it's showing the last draft in the loop, even though I'm resetting the query variable with wp_reset_query().

Thanks!

Here's my function:

// Get Company Drafts
add_action( 'admin_bar_menu', 'add_nodes_and_groups_to_toolbar', 1000 );
function add_nodes_and_groups_to_toolbar( $wp_admin_bar ) {

  $user_id = bp_loggedin_user_id();
  $draft_query = new WP_Query(array(
      'connected_type' => 'companies_to_users',
      'connected_items' => $user_id,
      'nopaging' => true,
      'post_status' => 'draft'
  ));

  if ($draft_query->have_posts()) {

    // Add 'Drafts' to the Toolbar
    $args = array(
        'id'    => 'drafts',
        'title' => 'Drafts',
    );
    $wp_admin_bar->add_node( $args );

    // Add the category 'Companies' as the sub-menu of Drafts 
    $args = array(
        'id'     => 'drafts_company',
        'title'  => 'Companies',
        'parent' => 'drafts'
    );
    $wp_admin_bar->add_node( $args );

    while($draft_query->have_posts()) : $draft_query->the_post();

        // Add the post title as the sub-menu of the category sub-menu
        $args = array(
            'id'     => $post->ID,
            'parent' => 'drafts_company',
            'title' =>  get_the_title(),
            'href'   => apply_filters('gform_update_post/edit_url', $post->ID, home_url('/edit-company/'))
        );

        $wp_admin_bar->add_node( $args );

    endwhile;
  }

  wp_reset_query();

}
2

The problem is that wp_reset_postdata attempts to restore $post from the main $wp_query, but on post.php in admin, $post isn't populated from $wp_query, so wp_reset_postdata fails to restore it. The solution is to use get_posts and a foreach instead of WP_Query and the loop.

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.