WPMU:以编程方式将CPT帖子添加到特定博客ID

时间:2021-05-24 作者:Athoxx

我试图通过编程将新闻稿从API添加到特定的子网站(博客ID)。

这个应用程序相当大,但为了解决这个问题,我已经对它进行了简化。它在WP Core外部运行,仅在运行时加载,通过wp-load.php.

require_once( "../wp-load.php" );

$blog_id = 2;
switch_to_blog( $blog_id );
$lang = \'en\';

$new_pr = wp_insert_post(
    array(
        \'post_author\'   => 1,
        \'post_status\'   => \'publish\',
        \'post_type\'     => \'pressreleases\',
        \'post_date\'         => $this->publish_date,
        \'post_content\'      => $this->body,
        \'post_title\'        => $this->title,
        \'tax_input\'         => array(
            \'pr_categories\'     => $this->pr_category_id
        )
    )
);
var_dump( get_current_blog_id() ); // This returns (int)2, just like it should.
restore_current_blog();
问题是:
无论我在$blog_id 变量,则版本将添加到ID为的日志中1.

我错过什么了吗?

1 个回复
最合适的回答,由SO网友:Athoxx 整理而成

我终于自己找到了答案。它由两部分组成:

我需要全球$switched 待定义$blog_id 因为那是保留的

require_once( "../wp-load.php" );

global $switched;
$blog_id_target = 2;
switch_to_blog($blog_id_target);

$lang = \'en\';

$new_pr = wp_insert_post(
    array(
        \'post_author\'   => 1,
        \'post_status\'   => \'publish\',
        \'post_type\'     => \'pressreleases\',
        \'post_date\'         => $this->publish_date,
        \'post_content\'      => $this->body,
        \'post_title\'        => $this->title,
        \'tax_input\'         => array(
            \'pr_categories\'     => $this->pr_category_id
        )
    )
);
var_dump( get_current_blog_id() ); // This returns (int)2, just like it should.
restore_current_blog();