我试图通过编程将新闻稿从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
.
我错过什么了吗?
最合适的回答,由SO网友:Athoxx 整理而成
我终于自己找到了答案。它由两部分组成:
我需要全球$switched
待定义日志id的变量不能为$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();