I am programming a hook for ACF to get a list of posts from another site in a network.
so
switch_to_blog(1);
... do some WP_Query...
...list results in an array ...
restore_current_blog;
in a filter add_filter('acf/load_field/name=industries', 'acf_load_choices');
but the switch_to_blog
is not working.
I can get raw results using the SQL within the WP_Query object. I can get the results if the current blog is 1
(as above) so I know my internal code is correct but not if the switch_to_blog is needed to do something.
Why is switch_to_blog
not available in this context?
My two functions, the first works, the second doesn't
function acf_load_industry_pages( $field ) {
// reset choices
$field['choices'] = array();
global $wpdb;
$language = pll_current_language();
switch_to_blog(1);
$top_parent = pll_get_post('160', $language);
restore_current_blog();
$page_query=" SELECT wp0_posts.*
FROM wp0_posts
LEFT JOIN wp0_term_relationships
ON (wp0_posts.ID = wp0_term_relationships.object_id)
WHERE wp0_posts.post_parent = ". $top_parent. "
AND (wp0_posts.post_type = 'page' )
AND (wp0_posts.post_status = 'publish')
GROUP BY wp0_posts.ID
ORDER BY wp0_posts.menu_order ASC";
$pages = $wpdb->get_results( $page_query);
if( is_array($pages) ) {
foreach( $pages as $page ) {
$field['choices'][ $page->ID ] = $page->post_title;
$parent = $page->ID;
$child_page_query=' SELECT wp0_posts.*
FROM wp0_posts
LEFT JOIN wp0_term_relationships
ON (wp0_posts.ID = wp0_term_relationships.object_id)
WHERE wp0_posts.post_parent ='. $parent.'
AND (wp0_posts.post_type = \'page\' )
AND (wp0_posts.post_status = \'publish\')
GROUP BY wp0_posts.ID
ORDER BY wp0_posts.menu_order ASC
';
$child_pages = $wpdb->get_results( $child_page_query);
if( is_array($child_pages) ) {
foreach ($child_pages as $page) {
$field['choices'][$page->ID] = $page->post_title;
}
}
}
}
// return the field
return $field;
}
// in development
function acf_load_industry_pages_wp_query( $field )
{
// reset choices
$field['choices'] = array();
global $wpdb;
$language = pll_current_language();
switch_to_blog(1);
$top_parent = pll_get_post('160', $language);
$args = array(
'post_type' => 'page',
'posts_per_page' => -1,
'post_parent' => $top_parent,
'lang' => $language,
);
$page_query = new WP_Query($args);
if ($page_query->have_posts()) {
while ($page_query->have_posts()) {
$page_query->the_post();
$field['choices'][get_the_ID()] = get_the_title();
}
}
wp_reset_postdata();
restore_current_blog();
// return the field
return $field;
}
pll_get_post()
do? In your first snippet, you're doing therestore_current_blog()
immediately after you usepll_get_post()
, so the rest of the code is run in the original site; in the second snippet, you onlyrestore_current_blog()
at the very end.