0
votes

i am using wordpress multisite. i am creating a function that when you post on 1 site, it will post the same post on another blog if required.

i am currently using switch_to_blog(), here is my code:

switch_to_blog(2);

$my_post = array(
  'post_title'    => $post_title,
  'post_content'  => $post_content,
  'post_status'   => 'publish',
  'post_author'   => $post_author,
  //'post_category' => array(8,39)
);

// Insert the post into the database
wp_insert_post( $my_post );

restore_current_blog();

the above is ran on a save_post action. it works fine and posts to both blogs. The only issue is on the blog i switch to wp_insert_post gets stuck in a loop and have thousands of posts added!

Any reason why that would happen from the above code?

1
Where is this code located? Which file and which hook? - brasofilo

1 Answers

0
votes

That's because wp_insert_post calls the action save_post, hence the loop. You have to remove the action, insert the post and add the action again.

The idea on how to control the first save is from Check for update vs new post on save_post action. Also see Why does save_post action fire when creating a new post?. I added a check for the post statuses of auto-draft and inherit.

<?php
/* Plugin Name: Publish to Network */

add_action( 'save_post', 'cross_publish_so_17611289', 10, 2 );

function cross_publish_so_17611289( $post_id, $post_object )
{
    if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
        return;

    if( defined( 'DOING_AJAX' ) && DOING_AJAX )
        return;

    # Block auto-drafts and revisions
    if( in_array( $post_object->post_status, array( 'auto-draft', 'inherit' ) ) )
        return;

    $termid = get_post_meta( $post_id, '_termid', true );

    # It's a new post
    if( empty( $termid ) )
    {
        update_post_meta( $post_id, '_termid', 'update' );
        remove_action( 'save_post', 'cross_publish_so_17611289' );
        switch_to_blog(2);
        $my_post = array(
          'post_title'    => $post_object->post_title,
          'post_content'  => $post_object->post_content,
          'post_status'   => 'publish',
          'post_author'   => $post_object->post_author,
        );
        wp_insert_post( $my_post );
        restore_current_blog();
        add_action( 'save_post', 'cross_publish_so_17611289', 10, 2 );
    }
}