Skip to content

Instantly share code, notes, and snippets.

@eduwass
Last active September 17, 2024 15:16
Show Gist options
  • Save eduwass/90c36565c41ac01cafe3 to your computer and use it in GitHub Desktop.
Save eduwass/90c36565c41ac01cafe3 to your computer and use it in GitHub Desktop.
Programmatically duplicating a WordPress post
<?php
/**
* Duplicates a post & its meta and returns the new duplicated Post ID.
*
* @param int $post_id The Post ID you want to clone.
* @return int The duplicated Post ID.
*/
function duplicate_post(int $post_id): int
{
$old_post = get_post($post_id);
if (!$old_post) {
// Invalid post ID, return early.
return 0;
}
$title = $old_post->post_title;
// Create new post array.
$new_post = [
'post_title' => $title,
'post_name' => sanitize_title($title),
'post_status' => 'draft',
'post_type' => $old_post->post_type,
];
// Insert new post.
$new_post_id = wp_insert_post($new_post);
// Copy post meta.
$post_meta = get_post_custom($post_id);
foreach ($post_meta as $key => $values) {
foreach ($values as $value) {
add_post_meta($new_post_id, $key, maybe_unserialize($value));
}
}
// Copy post taxonomies.
$taxonomies = get_post_taxonomies($post_id);
foreach ($taxonomies as $taxonomy) {
$term_ids = wp_get_object_terms($post_id, $taxonomy, ['fields' => 'ids']);
wp_set_object_terms($new_post_id, $term_ids, $taxonomy);
}
// Return new post ID.
return $new_post_id;
}
@entwane37
Copy link

entwane37 commented May 22, 2020

Thanks for this code.
I try to automatically duplicate a post when it's published, but it's duplicated twice.
An idea ?

Thanks in advance,

@entwane37
Copy link

entwane37 commented May 22, 2020

function modify_post_date( $post_id, $post, $update ) {
if( defined( 'DOING_AUTOSAVE' ) and DOING_AUTOSAVE ) { return; }
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) { return; }
if (wp_is_post_autosave($post_id)) { return; }
if( !$update ) { return; }
if ( !current_user_can( 'edit_post', $post_id ) ) { return; }
if( $post->post_type !== 'armoire' ) { return; }
if( wp_is_post_revision( $post_id ) ) { return; }
if( $post->post_status == 'publish' ) {
remove_action( 'save_post' , 'modify_post_date' , 10, 3 );
duplicate($post_id);
$new_date = $post->post_modified;
$old_date = $post->post_date;
$title = $post->post_title;
$current_user = wp_get_current_user();
$author = $current_user->ID;
wp_update_post( array( 'post_date' => $new_date ));
remove_action( 'save_post' , 'modify_post_date' , 10, 3 );
}
}
add_action( 'save_post' , 'modify_post_date' , 10, 3 );
?>

@AkramiPro
Copy link

it is important to unserialize data to avoid conflicts:

<?php

  /**
   * Duplicates a post & its meta and it returns the new duplicated Post ID
   * @param  [int] $post_id The Post you want to clone
   * @return [int] The duplicated Post ID
   */
  function duplicate($post_id) {
    $title   = get_the_title($post_id);
    $oldpost = get_post($post_id);
    $post    = array(
      'post_title' => $title,
      'post_status' => 'publish',
      'post_type' => $oldpost->post_type,
      'post_author' => 1
    );
    $new_post_id = wp_insert_post($post);
    // Copy post metadata
    $data = get_post_custom($post_id);
    foreach ( $data as $key => $values) {
      foreach ($values as $value) {
        add_post_meta( $new_post_id, $key, maybe_unserialize( $value ) );// it is important to unserialize data to avoid conflicts.
      }
    }

    return $new_post_id;
  }

@pixelbart
Copy link

pixelbart commented Dec 20, 2022

Very cool! Here is an addition, if you also want to copy the taxonomies:

function duplicate($post_id)
{
    $title = get_the_title($post_id);
    $oldpost = get_post($post_id);

    $post = [
        'post_title' => $title,
        'post_name' => sanitize_title($title),
        'post_status' => 'draft',
        'post_type' => $oldpost->post_type,
    ];

    $new_post_id = wp_insert_post($post);
    $data = get_post_custom($post_id);

    foreach ($data as $key => $values) {
        foreach ($values as $value) {
            add_post_meta($new_post_id, $key, maybe_unserialize($value));
        }
    }

    $taxonomies = get_post_taxonomies($post_id);

    if ($taxonomies) {
        foreach ($taxonomies as $taxonomy) {
            wp_set_object_terms(
                $new_post_id,
                wp_get_object_terms(
                    $post_id,
                    $taxonomy,
                    ['fields' => 'ids']
                ),
                $taxonomy
            );
        }
    }

    return $new_post_id;
}

@IPD8
Copy link

IPD8 commented May 23, 2023

its not working if page is created in builder like elementor, WP Bakery or Any other... any suggestion?

@eduwass
Copy link
Author

eduwass commented May 23, 2023

@IPD8

its not working if page is created in builder like elementor, WP Bakery or Any other... any suggestion?

It really depends on how the page builders are saving the content, if they rely only on post meta, in theory, it should work, but it's hard to say... If I were you I'd probably look into how the content is saved internally by the page builder.

@IPD8
Copy link

IPD8 commented May 24, 2023

@IPD8

its not working if page is created in builder like elementor, WP Bakery or Any other... any suggestion?

It really depends on how the page builders are saving the content, if they rely only on post meta, in theory, it should work, but it's hard to say... If I were you I'd probably look into how the content is saved internally by the page builder.

i am not 100% sure what is the reason, but when i checking DB is there, so its really duplicates full content, but if you will open directly its blank page, but if you will run it "edit with WP bakery" or any other editor and then save, it will work. so maybe something is still missing when i duplicate

@pixelbart
Copy link

@IPD8

The issue lies with the get_post_custom function, which disregards meta fields starting with an underscore. Page builders often store their data in fields with underscores, such as _elementor_X. To resolve this, you should utilize wpdb and the postmeta table. By doing so, everything should function correctly.

An example that I haven't tested myself could look like the one provided. It might help solve your issues. I just wrote this example, so you don't need to provide any references or citations here.

function duplicate($post_id)
{
    $title = get_the_title($post_id);
    $oldpost = get_post($post_id);

    $post = [
        'post_title' => $title,
        'post_name' => sanitize_title($title),
        'post_status' => 'draft',
        'post_type' => $oldpost->post_type,
    ];

    $new_post_id = wp_insert_post($post);

    global $wpdb;

    $table = $wpdb->postmeta;

    $meta_data = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT meta_key, meta_value FROM $table WHERE post_id = %d",
            $post_id,
        )
    );

    foreach ($meta_data as $meta) {
        $meta_key = $meta->meta_key;
        $meta_value = maybe_unserialize($meta->meta_value);
        add_post_meta($new_post_id, $meta_key, $meta_value);
    }

    $taxonomies = get_post_taxonomies($post_id);

    if ($taxonomies) {
        foreach ($taxonomies as $taxonomy) {
            wp_set_object_terms(
                $new_post_id,
                wp_get_object_terms(
                    $post_id,
                    $taxonomy,
                    ['fields' => 'ids']
                ),
                $taxonomy
            );
        }
    }

    return $new_post_id;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment