2

I am trying to create a plugin to copy a post to another site when a post is published in Worpdress Multisite environment using publish_post and wp_insert_post hook. The code is below

function copy_post_to_blog($post_id) {

   $post = get_post($post_id, ARRAY_A); // get the original post

   $post['ID'] = ''; // empty id field, to tell wordpress that this will be a new post

   switch_to_blog(main_blog_id()); // switch to target blog

   wp_insert_post($post); // insert the post

   restore_current_blog(); // return to original blog
}

add_action('publish_post', 'copy_post_to_blog');

The code is working and inserting post data to the blog but the problem is that loop does't stop inserting new post until I stop the browser loading execution myself. As it should stop after inserting post into database first time but it does't and starts inserting post infinitely. Please Help me how to get ride of this problem.

I am thankful to you in advance.

2
  • 1
    My guess is that this is running forever because you the publish_post is being called on the other site when insert_post is called. You can try to add the following as the first line if(get_current_blog_id() == main_blog_id()) { return; }. Add this before before $post = get_post Commented Mar 9, 2017 at 23:25
  • @czerspalace thank you. it is really help full, but can you give me an example?
    – Syed Aqeel
    Commented Mar 23, 2017 at 10:30

1 Answer 1

1

The wp_insert_post() function triggers the publish_post hook again leading to an infinite loop. Try this change:

remove_action('publish_post', 'copy_post_to_blog');
wp_insert_post($post);
add_action('publish_post', 'copy_post_to_blog');
1
  • Oh.... that's the reason it is an infinite loop... Thank you. Please can you give me a complete example so I can understand.
    – Syed Aqeel
    Commented Mar 23, 2017 at 10:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.