'draft', 'suffix' => ' (Copy)', 'author' => 'current', ) ); $status = self::resolve_status( $post, $args['status'] ); // Always separate the suffix from the title with one space, whatever was typed in the settings. $args['suffix'] = trim( (string) $args['suffix'] ); $args['suffix'] = '' === $args['suffix'] ? '' : ' ' . $args['suffix']; if ( 'product' === $post->post_type && function_exists( 'wc_get_product' ) ) { $new_id = self::duplicate_product( $post, $args['suffix'], $status ); } else { $new_id = self::duplicate_post( $post, $args['suffix'], $status, $args['author'] ); } if ( is_wp_error( $new_id ) ) { return $new_id; } if ( ! $new_id ) { return new \WP_Error( 'toolvane_duplicate_failed', __( 'Duplication failed.', 'toolvane' ) ); } clean_post_cache( $new_id ); /** * Fires after a post was duplicated. * * @param int $new_id New post ID. * @param int $old_id Original post ID. * @param \WP_Post $post Original post. */ do_action( 'toolvane_post_duplicated', $new_id, $post->ID, $post ); return $new_id; } /** * Picks a status the current user is allowed to set. * * @param \WP_Post $post Original post. * @param string $status Requested status. * @return string */ private static function resolve_status( \WP_Post $post, $status ) { $type = get_post_type_object( $post->post_type ); if ( 'same' === $status ) { $status = in_array( $post->post_status, array( 'publish', 'future', 'private', 'pending', 'draft' ), true ) ? $post->post_status : 'draft'; if ( 'future' === $status ) { $status = 'draft'; } } if ( ! in_array( $status, array( 'draft', 'pending', 'private', 'publish' ), true ) ) { $status = 'draft'; } if ( in_array( $status, array( 'publish', 'private' ), true ) && ( ! $type || ! current_user_can( $type->cap->publish_posts ) ) ) { $status = 'draft'; } return $status; } /** * Generic post duplication. * * @param \WP_Post $post Original post. * @param string $suffix Title suffix. * @param string $status Status of the copy. * @param string $author Author mode. * @return int|\WP_Error */ private static function duplicate_post( \WP_Post $post, $suffix, $status, $author ) { $type = get_post_type_object( $post->post_type ); $author_id = get_current_user_id(); if ( 'original' === $author && $type && current_user_can( $type->cap->edit_others_posts ) ) { $author_id = (int) $post->post_author; } $data = array( 'post_title' => $post->post_title . $suffix, 'post_content' => $post->post_content, 'post_content_filtered' => $post->post_content_filtered, 'post_excerpt' => $post->post_excerpt, 'post_status' => $status, 'post_type' => $post->post_type, 'post_author' => $author_id, 'post_parent' => $post->post_parent, 'post_mime_type' => $post->post_mime_type, 'menu_order' => $post->menu_order, 'comment_status' => $post->comment_status, 'ping_status' => $post->ping_status, 'post_password' => $post->post_password, 'to_ping' => $post->to_ping, ); /** * Filters the post data used to create the copy. * * @param array $data Data passed to wp_insert_post(). * @param \WP_Post $post Original post. */ $data = apply_filters( 'toolvane_duplicate_post_data', $data, $post ); $new_id = wp_insert_post( wp_slash( $data ), true ); if ( is_wp_error( $new_id ) || ! $new_id ) { return $new_id; } self::copy_terms( $post, $new_id ); self::copy_meta( $post->ID, $new_id ); self::copy_language( $post, $new_id ); // Save once more so plugins that index on save_post (Yoast SEO, Rank Math, search plugins) see the copied meta. // An empty page_template keeps the copied template meta untouched. wp_update_post( array( 'ID' => $new_id, 'page_template' => '', ) ); self::copy_aioseo( $post->ID, $new_id ); self::clear_builder_caches( $new_id ); return $new_id; } /** * Copies all taxonomy terms. * * @param \WP_Post $post Original post. * @param int $new_id New post ID. */ private static function copy_terms( \WP_Post $post, $new_id ) { $skip = self::SKIP_TAXONOMIES; if ( function_exists( 'pll_set_post_language' ) ) { $skip[] = 'language'; // Set through the Polylang API instead. } foreach ( get_object_taxonomies( $post->post_type ) as $taxonomy ) { if ( in_array( $taxonomy, $skip, true ) ) { continue; } $terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids', 'orderby' => 'term_order', ) ); if ( ! is_wp_error( $terms ) && $terms ) { wp_set_object_terms( $new_id, array_map( 'intval', $terms ), $taxonomy ); } } } /** * Meta keys skipped during duplication. * * @return string[] */ public static function skip_meta_keys() { /** * Filters meta keys that are not copied. * * @param string[] $skip Meta keys. */ return (array) apply_filters( 'toolvane_duplicate_skip_meta', self::SKIP_META ); } /** * Copies every meta row unchanged. * * Raw values are inserted directly, so serialized arrays, objects of classes that are not loaded, * JSON (Elementor, Bricks) and strings with backslashes keep their exact bytes. * * @param int $old_id Original post ID. * @param int $new_id New post ID. */ private static function copy_meta( $old_id, $new_id ) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Raw values are required for an exact copy; the cache is cleared below. $rows = $wpdb->get_results( $wpdb->prepare( "SELECT meta_key, meta_value FROM {$wpdb->postmeta} WHERE post_id = %d ORDER BY meta_id ASC", $old_id ) ); if ( ! $rows ) { return; } $skip = self::skip_meta_keys(); // Remove meta that wp_insert_post() or other plugins already added to the copy, so nothing is doubled. $keys = array_unique( wp_list_pluck( $rows, 'meta_key' ) ); foreach ( $keys as $key ) { if ( ! in_array( $key, $skip, true ) ) { delete_post_meta( $new_id, $key ); } } foreach ( $rows as $row ) { if ( in_array( $row->meta_key, $skip, true ) || 0 === strpos( $row->meta_key, '_wp_trash_' ) ) { continue; } // $wpdb->insert() stores the raw value exactly as read, without slashing or serializing it again. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Exact copy of raw meta values; the cache is cleared below. $wpdb->insert( $wpdb->postmeta, array( 'post_id' => $new_id, 'meta_key' => $row->meta_key, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Insert, not a query. 'meta_value' => $row->meta_value, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Insert, not a query. ), array( '%d', '%s', '%s' ) ); } wp_cache_delete( $new_id, 'post_meta' ); } /** * Keeps the language of the original with WPML or Polylang. * * @param \WP_Post $post Original post. * @param int $new_id New post ID. */ private static function copy_language( \WP_Post $post, $new_id ) { // Polylang. if ( function_exists( 'pll_get_post_language' ) && function_exists( 'pll_set_post_language' ) ) { $lang = pll_get_post_language( $post->ID ); if ( $lang ) { pll_set_post_language( $new_id, $lang ); } return; } // WPML. if ( defined( 'ICL_SITEPRESS_VERSION' ) ) { // phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- WPML public API hooks. $element_type = apply_filters( 'wpml_element_type', $post->post_type ); $details = apply_filters( 'wpml_element_language_details', null, array( 'element_id' => $post->ID, 'element_type' => $post->post_type, ) ); if ( is_object( $details ) && ! empty( $details->language_code ) ) { do_action( 'wpml_set_element_language_details', array( 'element_id' => $new_id, 'element_type' => $element_type, 'trid' => false, 'language_code' => $details->language_code, ) ); } // phpcs:enable } } /** * Copies the All in One SEO row, which is stored in a custom table. * * @param int $old_id Original post ID. * @param int $new_id New post ID. */ private static function copy_aioseo( $old_id, $new_id ) { global $wpdb; if ( ! function_exists( 'aioseo' ) ) { return; } $table = $wpdb->prefix . 'aioseo_posts'; // phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- All in One SEO table, the name is built from the trusted prefix. if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table ) ) ) !== $table ) { return; } $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE post_id = %d', $table, $old_id ), ARRAY_A ); if ( ! $row ) { return; } unset( $row['id'] ); $row['post_id'] = $new_id; $now = current_time( 'mysql', true ); if ( array_key_exists( 'created', $row ) ) { $row['created'] = $now; } if ( array_key_exists( 'updated', $row ) ) { $row['updated'] = $now; } $wpdb->delete( $table, array( 'post_id' => $new_id ), array( '%d' ) ); $wpdb->insert( $table, $row ); // phpcs:enable } /** * Makes page builders regenerate their CSS and asset caches for the copy. * * @param int $new_id New post ID. */ private static function clear_builder_caches( $new_id ) { // Beaver Builder. if ( class_exists( 'FLBuilderModel' ) && method_exists( 'FLBuilderModel', 'delete_all_asset_cache' ) ) { \FLBuilderModel::delete_all_asset_cache( $new_id ); } // Elementor: the post CSS file is created on first view because _elementor_css was not copied. if ( did_action( 'elementor/loaded' ) && class_exists( '\Elementor\Core\Files\CSS\Post' ) ) { $css = \Elementor\Core\Files\CSS\Post::create( $new_id ); if ( method_exists( $css, 'delete' ) ) { $css->delete(); } } } /** * Uses WooCommerce's own duplicator so variations, stock and lookup tables stay correct. * * @param \WP_Post $post Original product post. * @param string $suffix Title suffix. * @param string $status Status of the copy. * @return int|\WP_Error */ private static function duplicate_product( \WP_Post $post, $suffix, $status ) { $product = wc_get_product( $post->ID ); if ( ! $product ) { return new \WP_Error( 'toolvane_no_product', __( 'Product not found.', 'toolvane' ) ); } if ( ! class_exists( 'WC_Admin_Duplicate_Product' ) ) { include_once WC()->plugin_path() . '/includes/admin/class-wc-admin-duplicate-product.php'; } $exclude = static function ( $keys ) { return array_unique( array_merge( (array) $keys, self::skip_meta_keys() ) ); }; add_filter( 'woocommerce_duplicate_product_exclude_meta', $exclude ); $duplicator = new \WC_Admin_Duplicate_Product(); $copy = $duplicator->product_duplicate( $product ); remove_filter( 'woocommerce_duplicate_product_exclude_meta', $exclude ); if ( ! $copy ) { return 0; } $copy->set_name( $product->get_name() . $suffix ); $copy->set_status( $status ); $copy->save(); self::copy_language( $post, $copy->get_id() ); self::copy_aioseo( $post->ID, $copy->get_id() ); self::clear_builder_caches( $copy->get_id() ); return $copy->get_id(); } }