I’m trying to programmatically add press releases from an API, to specific sub sites (blog ID’s).
The application is quite large, but I’ve boiled it down for the purposes of this question. It runs outside of WP Core, only loading it while running, through 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();
Here’s the problem:
No matter what I put in the $blog_id variable, the release gets added to the blog with ID 1.
Am I missing something here?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
I finally found the answer myself. It’s two parts:
- I need the global
$switchedto be defined. - The variable for blog id can’t be
$blog_idbecause that’s reserved.
The above code should thus be the following.
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();
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0