• dan400o6

    (@dan400o6)


    Hi, how can I duplicate a post via an API call? I’ve view the API documentation and only saw things in regards to creating and editing post. I’m also using elementor

Viewing 4 replies - 1 through 4 (of 4 total)
  • catacaustic

    (@catacaustic)

    There’s no functions built in to duplicate posts. You’d have to write that manually yourself.

    That’s not too hard though. You’d just need to get the posts content and meta values, and save them in the remote site.

    Moderator bcworkz

    (@bcworkz)

    To rephrase catacaustic with a bit more specificity: You can GET a post’s data with wp-json/wp/v2/posts/<id>. Strip out the id field from the returned data. If you are cloning to the same site, alter the slug field value so it’ll be unique. Then POST the data to the appropriate WP API (the same or remote) at wp-json/wp/v2/posts

    Thread Starter dan400o6

    (@dan400o6)

    Ok, so I have a plugin called premium add-ons, it has a feature to duplicate a post exactly how I want, only problem is I can’t do it from the API so I’m trying to add that functionality.

    I think if I can pass the post correctly, this plugin will take care of it.

    Heres the API route I created, in my functions.php.

    add_action( 'rest_api_init', function () {
        register_rest_route( 'duplicatePost/v1', 'posts/(?P<id>\d+)', array(
        'methods' => 'POST',
        'callback' => 'duplicate_post',
      ) );
    } );

    Here is the function I’m trying to pass the request to:

    	public function duplicate_post(WP_REST_Request $request) {
    	
            $post = get_post($request['post_id']);
    
    		$post = sanitize_post( $post, 'db' );
    
    		$duplicated_post_id = self::insert_post( $post );
    		
    		if ( ! is_wp_error( $duplicated_post_id ) ) {
    
    			self::duplicate_post_taxonomies( $post, $duplicated_post_id );
    			self::duplicate_post_meta_data( $post, $duplicated_post_id );
    			
    		}
    		die();
    	}
    Moderator bcworkz

    (@bcworkz)

    duplicate_post() is a class method, you can’t call it directly. Try making your own callback function which instantiates a new class object, then calls that object’s method.

    Frankly I think my earlier suggestion would be easier, but you need to do what makes sense to you. Additionally, my suggestion is untested. I’ve every reason to expect it to work, but I’ve never had a need to duplicate posts.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Duplicate a post from REST API’ is closed to new replies.