get_post_meta fails after switch_to_blog


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) ) {
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


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()?

Read more here: get_post_meta fails after switch_to_blog

Leave a Reply

Your email address will not be published. Required fields are marked *