• Resolved dekket

    (@dekket)


    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?

Viewing 1 replies (of 1 total)
  • Thread Starter dekket

    (@dekket)

    I finally found the answer myself. Posting it here for anyone who stumbles across this in the future.

    It’s two parts essentially:

    1) I need the global $switched to be defined.
    2) The variable for blog id can’t be $blog_id because that’s reserved.

    The above code should thus be the following.

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

    Also worthy to note:

    I’m running the wp_insert_post() within another function, which is within a custom class. $switched needs to be present there as well, and the switch_to_blog() must also be called within that function.

Viewing 1 replies (of 1 total)
  • The topic ‘Programmatically adding new CPT posts to specific blog ID within Multisite’ is closed to new replies.