0

When I save/publish a page, I want it to save to all blogs in multisite including its custom fields (using Advance custom fields). The problem is that, when I tried to look at the value of post_meta during saving before passing it to every blog, it only contains edit_lock. But upon checking the database after the saving of the page, the meta key and value are in the post_meta table already. I tried modifying the priority but still the same. What could be the problem?

add_action( 'save_post', 'savetoall', 20, 2 );

function savetoall( $original_post_id, $original_post )
{
    if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return $original_post_id;


    if( get_post_status( $original_post ) !== 'publish' ) return $original_post_id;


    remove_action('save_post', __FUNCTION__);

    if ($original_post_id && get_current_blog_id() == 1) 
    {


    global $wpdb;
    $blogs = $wpdb->get_results( $wpdb->prepare("SELECT blog_id FROM $wpdb->blogs WHERE site_id = %d AND public = '1' AND archived = '0' AND mature = '0' AND spam = '0' AND deleted = '0' ORDER BY blog_id ASC", $wpdb->siteid), ARRAY_A );
    $blog_ids = array();

    foreach($blogs as $blog)
    {
        array_push($blog_ids, $blog['blog_id']);
    }


    $post_data = array(
    'post_author' => $original_post->post_author,
    'post_date' => $original_post->post_date,
    'post_modified' => $original_post->post_modified,
    'post_content' => $original_post->post_content,
    'post_title' => $original_post->post_title,
    'post_excerpt' => $original_post->post_excerpt,
    'post_status' => 'publish',
    'post_name' => $original_post->post_name,
    'post_type' => $original_post->post_type,
     );


     $post_terms = wp_get_object_terms( $original_post_id, 'category', array('fields' => 'slugs') );
     $post_meta = get_post_custom( $original_post_id );
     //the value of post meta here is only edit_lock. 

     foreach( $blog_ids as $blog_id ) 
     {

         switch_to_blog( $blog_id );


         if( get_posts( array( 'name' => $post_data['post_name'], 'post_type' => $post_data['post_type'], 'post_status' => 'publish' ) ) ) 
         {
         restore_current_blog();
         continue;
         }

         $inserted_post_id = wp_insert_post($post_data);

         wp_set_object_terms( $inserted_post_id, $post_terms, 'category', false);
         $attachments = get_blog_post( 1, $meta_value );

        foreach ( $post_meta as $meta_key => $meta_values) 
        {

            if( $meta_key == '_wp_old_slug' ) {
                continue;
            }
            foreach ($meta_values as $meta_value) {
                add_post_meta( $inserted_post_id, $key, $meta_value );
            }
        }

        restore_current_blog();

     }
     }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.