wordpress使用switch_to_blog

时间:2013-07-12 09:07:11

标签: php wordpress

我正在使用wordpress多站点。我正在创建一个功能,当您在1个网站上发布时,如果需要,它会在另一个博客上发布相同的帖子。

我目前正在使用switch_to_blog(),这是我的代码:

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

以上是在save_post操作上运行的。它工作正常,并发布到两个博客。唯一的问题是在博客上我切换到wp_insert_post卡在一个循环中并添加了数千个帖子!

上述代码会发生什么原因?

1 个答案:

答案 0 :(得分:0)

那是因为wp_insert_post调用了动作save_post,因此循环。您必须删除操作,插入帖子并再次添加操作。

如何控制第一次保存的想法来自Check for update vs new post on save_post action。另请参阅Why does save_post action fire when creating a new post?。我添加了对auto-draftinherit的帖子状态的检查。

<?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 );
    }
}