I am using following code to duplicate woocommerce products.
add_action('cred_save_data_713', 'duplicate_post', 10, 2);
function duplicate_post($post_id, $form_data) {
// get data of original post
$post = get_post( $form_data['container_id'], ARRAY_A );
// update Post Status to PENDING
$post['post_status'] = 'pending';
// update the new post with this data
$post['ID'] = $post_id;
$post['post_title'] = 'Copy of ' . $post['post_title'];
wp_update_post( $post );
// get fields of original post
$fields = get_post_custom( $form_data['container_id'] );
// update the new post with these fields
foreach ($fields as $key => $values) {
foreach ($values as $value) {
add_post_meta($post_id, $key, $value, false);
}
}
}
when duplicating a product, the post author is also duplicated. what i want to achieve is to duplicate the post but the Author should be the current user ho has duplicated the post. how can i modify this with my code?
You can use get_current_user_id() to get the id of the current user and use that to update the post_author before creating the duplicate. Your edited code would look something like this:
add_action('cred_save_data_713', 'duplicate_post', 10, 2);
function duplicate_post($post_id, $form_data) {
// get data of original post
$post = get_post( $form_data['container_id'], ARRAY_A );
// update Post Status to PENDING
$post['post_status'] = 'pending';
// set author as current user
$author_id = get_current_user_id();
$post['post_author'] = $author_id;
// update the new post with this data
$post['ID'] = $post_id;
$post['post_title'] = 'Copy of ' . $post['post_title'];
wp_update_post( $post );
// get fields of original post
$fields = get_post_custom( $form_data['container_id'] );
// update the new post with these fields
foreach ($fields as $key => $values) {
foreach ($values as $value) {
add_post_meta($post_id, $key, $value, false);
}
}
}