Back to all posts

Easy Post Duplicator Plugin for WordPress


To get started, create a new plugin by creating a new directory in the WordPress plugins directory and adding a PHP file (duplicate_post.php) with the following code:

<?php

/**
 * Plugin Name: Duplicate Post Plugin
 * Description: Adds a "Duplicate Post" button to the action row in the post editor.
 * Version: 1.0
 * Author: Chethan S Poojary
 * Author URI: https://sentensecase.com/
 */

// Add the "Duplicate Post" button to the action row in the post editor.

if (!defined('ABSPATH')) {
    exit;
}

function duplicate_post_add_button($actions, $post)
{
    if (current_user_can('edit_posts')) {
        $actions['duplicate_post'] = '<a href="' . esc_url(wp_nonce_url('admin.php?action=duplicate_post&post=' . $post->ID, 'duplicate_post')) . '">Duplicate Post</a>';
    }
    return $actions;
}
add_filter('post_row_actions', 'duplicate_post_add_button', 10, 2);

// Handle the "Duplicate Post" button click.
function duplicate_post_handle_button()
{
    if (isset($_GET['action']) && $_GET['action'] == 'duplicate_post' && isset($_GET['post']) && wp_verify_nonce($_GET['_wpnonce'], 'duplicate_post')) {
        $post_id = absint($_GET['post']);
        $post = get_post($post_id);
        if ($post && !is_wp_error($post)) {
            $new_post = array(
                'post_title' => $post->post_title,
                'post_content' => $post->post_content,
                'post_status' => 'draft',
                'post_type' => $post->post_type,
                'post_author' => $post->post_author,
                'post_parent' => $post->post_parent,
                'post_excerpt' => $post->post_excerpt,
                'post_password' => $post->post_password
            );

            $thumbnail_id = get_post_thumbnail_id($post->ID);
            if ($thumbnail_id) {
                $image_url = wp_get_attachment_image_src($thumbnail_id, 'full');
                $new_post['post_thumbnail'] = $image_url[0];
            }

            $new_post_id = wp_insert_post($new_post);
            if ($new_post_id) {
                $new_post_permalink = get_permalink($new_post_id);
                wp_redirect(admin_url('post.php?action=edit&post=' . $new_post_id));
                exit;
            }
        }
    }
}
add_action('admin_action_duplicate_post', 'duplicate_post_handle_button');