&_wpnonce= */ defined( 'ABSPATH' ) || exit; class AumNexCart_Duplicate { const ACTION = 'aumnexcart_duplicate'; const NONCE_PREFIX = 'aumnexcart_duplicate_'; public function __construct() { add_filter( 'post_row_actions', array( $this, 'add_row_action' ), 10, 2 ); add_action( 'admin_action_' . self::ACTION, array( $this, 'handle' ) ); } /** * @param array $actions * @param WP_Post $post * @return array */ public function add_row_action( $actions, $post ) { if ( AumNexCart_Post_Type::POST_TYPE !== $post->post_type ) { return $actions; } if ( ! current_user_can( 'edit_post', $post->ID ) ) { return $actions; } $url = wp_nonce_url( admin_url( 'admin.php?action=' . self::ACTION . '&post=' . $post->ID ), self::NONCE_PREFIX . $post->ID ); $actions['aumnexcart_duplicate'] = '' . esc_html__( 'Duplicate', 'aumnexcart' ) . ''; return $actions; } /** * Handles the duplicate admin action. */ public function handle() { $post_id = isset( $_GET['post'] ) ? absint( $_GET['post'] ) : 0; if ( ! $post_id ) { wp_die( esc_html__( 'Missing post ID.', 'aumnexcart' ) ); } check_admin_referer( self::NONCE_PREFIX . $post_id ); if ( ! current_user_can( 'edit_post', $post_id ) ) { wp_die( esc_html__( 'You are not allowed to duplicate this product.', 'aumnexcart' ) ); } $original = get_post( $post_id ); if ( ! $original || AumNexCart_Post_Type::POST_TYPE !== $original->post_type ) { wp_die( esc_html__( 'Invalid product.', 'aumnexcart' ) ); } $new_id = self::duplicate_post( $original ); if ( is_wp_error( $new_id ) ) { wp_die( esc_html( $new_id->get_error_message() ) ); } wp_safe_redirect( admin_url( 'post.php?action=edit&post=' . $new_id ) ); exit; } /** * Performs the duplication. Static so the migration / import * tools can reuse it. * * @param WP_Post $original * @return int|WP_Error */ public static function duplicate_post( $original ) { $new = array( 'post_title' => $original->post_title . ' ' . __( '(Copy)', 'aumnexcart' ), 'post_content' => $original->post_content, 'post_excerpt' => $original->post_excerpt, 'post_status' => 'draft', 'post_type' => $original->post_type, 'post_author' => get_current_user_id(), ); $new_id = wp_insert_post( $new, true ); if ( is_wp_error( $new_id ) ) { return $new_id; } /* Featured image */ $thumb = get_post_thumbnail_id( $original->ID ); if ( $thumb ) { set_post_thumbnail( $new_id, $thumb ); } /* Plugin meta */ AumNexCart_Meta::save_media( $new_id, AumNexCart_Meta::get_media( $original->ID ) ); AumNexCart_Meta::save_price( $new_id, AumNexCart_Meta::get_price( $original->ID ) ); AumNexCart_Meta::save_attributes( $new_id, AumNexCart_Meta::get_attributes( $original->ID ) ); AumNexCart_Meta::save_contact( $new_id, AumNexCart_Meta::get_contact( $original->ID ) ); /* Taxonomy terms */ $terms = wp_get_object_terms( $original->ID, AumNexCart_Post_Type::TAXONOMY, array( 'fields' => 'ids' ) ); if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) { wp_set_object_terms( $new_id, $terms, AumNexCart_Post_Type::TAXONOMY ); } return $new_id; } }