I have a strange problem I’m facing when using WP_Query with multisite in a plugin I’m writing which hooks into add_meta_boxes. I’m wanting to display all post titles in a dropdown in a meta box.
While adding or editing a post in blog no. 2 (it could be any blog no.), I am looping through blog no. 1 and getting post titles from a custom post type to populate in a select dropdown. This works as it should, but in the process, the text in my excerpt is been replaced with the excerpt in the last post of the loop.
I have disabled all plugins. I have enabled 2015 theme on all sites. I’m using wordpress 4.1. I have tried with just posts instead of custom posts and the problem still exists. Below is the code I am using:
switch_to_blog( 1 );
$qry_args = array(
'post_status' => 'publish',
'post_type' => $typenow,
'posts_per_page' => -1,
);
$blog_query = new WP_Query( $qry_args );
if ( $blog_query->have_posts() ) {
while ( $blog_query->have_posts() ) {
$blog_query->the_post();
// get_the_ID(); and put in in an <option></option>
}
}
wp_reset_postdata();
restore_current_blog();
I have narrowed the source of the problem down to the line $blog_query->the_post();
Can anybody point out why my excerpt in a post in blog 2 is being replaced with an excerpt from a post in blog 1 while looping through blog 1? I’m rather new to writing plugins, so perhaps I’m doing something wrong that I know nothing about.
Thank you for your help,
Adrian
EDIT:
I just done some more tests, and found i was getting the following php warning with the plugin Query Monitor:
PHP error:
Trying to get property of non-objectCount:
6Location:
wp-includes/capabilities.php:1203Call Stack:
map_meta_cap()
WP_User->has_cap()
current_user_can()
meta_form()
post_custom_meta_box()
do_meta_boxes()
When I place the above code in admin_footer instead of add_meta_boxes the problem is fixed. So it appears to be possibly a timing issue?? If so, how can I query my posts in add_meta_boxes?