I have some code for custom cron in wordpress multisite, that from each blog site, gets their posts and postmeta data and put them on an xml structure.
But, when I retrive metadata (using get_post_meta
) from each blog (using switch_to_blog
), I get the data from the principal site (blog_id=1) not from the site I would like (for instance blog_id=33)
This is an example of part of my code:
function generate_xml(33);
function generate_xml($blog_id){
global $wpdb;
$change_ok = switch_to_blog($blog_id);
if ( is_wp_error($change_ok) ) {
WriteErrorLog($change_ok->get_error_message());
}
else {
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><data></data>', null, false);
$Body = $xml->addChild('Body');
$add_adverts = $Body->addChild('add_adverts');
$sql_posts = "select id, post_title, post_content from wp_".$blog_id."_posts where post_type = 'custom_add' and post_status = 'publish'";
$result_posts = $wpdb->get_results ($sql_posts);
foreach ( $result_posts as $data_posts ){
$post_id_loop = $data_posts->id;
$advert = $add_adverts->addChild('advert');
//...
$price = get_post_meta($post_id_loop, '_price', true);
$advert->addChild('price', $price);
$color = get_post_meta($post_id_loop, '_color', true);
$advert->addChild('color', $color);
$size = get_post_meta($post_id_loop, '_size', true);
$advert->addChild('size', $size);
//...
}
}
//... more code
restore_current_blog();
}
A summary of the data in the database tables is this:
But, the data I get are these:
How can I use get_post_meta()
on each site blog after do it switch_to_blog()
?
$add_adverts = $Body->addChild('add_adverts');
, addecho $blog_id;
and check if 33 is outputted. EDIT: Also, blog id 1 would have tablewp_posts
and 2 haswp_2_posts
so you need to adjust your code accordingly in case you want to use this function for blog with ID 1. Just a note.echo get_current_blog_id();
. The reason to useget_post_meta
is to avoid using$sql = "select meta_value from wp_".$blog_id."_postmeta where post_id=".$blog_id; $result = $wpdb->get_results ($sql); ....etc.
$wpdb
to get your posts instead of usingget_posts()
?get_posts()
. Can I filter, for example by post-type and/or post-status?