Selljam logo

How to Duplicate WordPress Post Without a Plugin: A Complete Tutorial

Learn how to create a snippet that will allow you to copy Wordpress posts easily. Ok, so you will need a plugin called Snippets but it's one worth having as it allows you to extend the functionality of Wordpress easily

I was looking for a quick and easy way to duplicate a template post for my online course creation challenge and didn't want to install another plugin. I already had the Snippets plugin installed so just needed to add this code as a new snippet and it was good to go!

Duplicating a WordPress post can be incredibly useful, especially when you want to reuse content or maintain a consistent format across multiple posts. While there are many plugins available to accomplish this task, some users prefer a more streamlined approach without adding extra plugins to their site. In this tutorial, we'll walk you through the process of duplicating a WordPress post using a custom code snippet. This method is efficient, easy to implement, and ensures that all your post data is copied accurately.

Let's look at how to duplicate a WordPress post without a plugin.

Steps to Create the Snippet

First off, you'll need to have the Snippets plugin installed already. This is the plugin needed to run the snippets of code either in the frontend or backend. Once installed you can add all sorts of custom functionality using Snippets in the future, so it's worth having.

  1. Open the Code Snippets Plugin:
    • Go to your WordPress dashboard.
    • Navigate to the plugin: Snippets > Add New
  2. Add the Custom Function:
    • Title your snippet, e.g., "Duplicate Post Function".
    • Add the following code to the snippet area:
function my_duplicate_post($post_id) {
    // Check if the user has the necessary capability
    if (!current_user_can('edit_posts')) {
        return;
    }

    // Get the original post
    $post = get_post($post_id);

    // Create a new post object with the original post's data
    $new_post = array(
        'post_title'    => $post->post_title . ' (Copy)',
        'post_content'  => $post->post_content,
        'post_status'   => 'draft', // Set the status of the new post to draft
        'post_author'   => get_current_user_id(),
        'post_type'     => $post->post_type
    );

    // Insert the new post into the database
    $new_post_id = wp_insert_post($new_post);

    // Copy taxonomies, meta data, etc.
    $taxonomies = get_object_taxonomies($post->post_type); // Get the taxonomies associated with the post type
    foreach ($taxonomies as $taxonomy) {
        $terms = wp_get_post_terms($post_id, $taxonomy, array('fields' => 'ids'));
        wp_set_object_terms($new_post_id, $terms, $taxonomy);
    }

    $post_meta = get_post_meta($post_id);
    foreach ($post_meta as $meta_key => $meta_values) {
        foreach ($meta_values as $meta_value) {
            // Handle specific Rank Math meta data if needed
            if (strpos($meta_key, 'rank_math') === false) {
                add_post_meta($new_post_id, $meta_key, $meta_value);
            }
        }
    }

    // Handle Rank Math specific data
    $rank_math_meta = [
        'rank_math_title',
        'rank_math_description',
        'rank_math_focus_keyword',
        'rank_math_canonical_url',
        // Add any other Rank Math fields you use
    ];

    foreach ($rank_math_meta as $meta_key) {
        $meta_value = get_post_meta($post_id, $meta_key, true);
        if ($meta_value) {
            add_post_meta($new_post_id, $meta_key, $meta_value);
        }
    }

    // Redirect to the edit screen for the new draft post
    wp_redirect(admin_url('post.php?action=edit&post=' . $new_post_id));
    exit;
}

function my_duplicate_post_link($actions, $post) {
    if (current_user_can('edit_posts')) {
        $actions['duplicate'] = '<a href="' . wp_nonce_url('admin.php?action=my_duplicate_post&post=' . $post->ID, basename(__FILE__), 'duplicate_nonce') . '" title="Duplicate this item" rel="permalink">Duplicate</a>';
    }
    return $actions;
}
add_filter('post_row_actions', 'my_duplicate_post_link', 10, 2);
add_filter('page_row_actions', 'my_duplicate_post_link', 10, 2);

function my_duplicate_post_action() {
    if (!isset($_GET['post']) || !isset($_GET['duplicate_nonce']) || !wp_verify_nonce($_GET['duplicate_nonce'], basename(__FILE__))) {
        return;
    }

    $post_id = absint($_GET['post']);
    my_duplicate_post($post_id);
}
add_action('admin_action_my_duplicate_post', 'my_duplicate_post_action');

Save and Activate the Snippet:

  • Ensure that the snippet is set to run only in the "backend" WordPress admin area.
  • Save and activate the snippet.

Explanation of the Code

  • Function: my_duplicate_post: This function handles the duplication of the post, copying the title, content, taxonomies, and meta data. It sets the new post's status to draft and redirects to the edit screen for the new post.
  • Function: my_duplicate_post_link: This function adds a "Duplicate" link to the row actions in the posts/pages list table.
  • Function: my_duplicate_post_action: This function handles the duplication action, verifying the nonce for security and calling the my_duplicate_post function with the post ID.

How to Use

  1. Go to Posts/Pages List:
    • Navigate to Posts or Pages in the WordPress admin dashboard.
  2. Duplicate a Post/Page:
    • Find the post or page you want to duplicate.
    • Hover over the post/page title, and you will see a "Duplicate" link in the row actions.
    • Click the "Duplicate" link to create a copy of the post/page.

Why Duplicate a WordPress Post without a Plugin?

Making a copy of a WordPress post can save you a lot of time and effort, particularly if you frequently create similar content. Here are a few scenarios where duplicating a post can be beneficial:

  • Consistent Formatting: Maintain the same layout, structure, and style across multiple posts.
  • Speed Up Content Creation: Quickly generate new posts without starting from scratch each time.
  • Preserve SEO Settings: Ensure that all your SEO settings, such as those configured with Rank Math, are carried over to the new post.

Testing the Duplicate Post Functionality

Once you've added and customized the code, it's time to test it.

  • Test the duplication process.
  • Verify that all post data, including meta data and SEO settings, are correctly copied.
  • Troubleshoot any issues that may arise during the testing phase.

Benefits of Using Custom Code Over Plugins

Using custom code to duplicate a post has several advantages over relying on plugins:

  • Performance: Reduce the number of plugins on your site, leading to faster load times and better performance.
  • Control: Have complete control over the functionality and customization of the duplication process.
  • Security: Minimize potential security risks associated with third-party plugins.

Conclusion

Hope this helps. Duplicating a WordPress post without a plugin is a powerful way to streamline your content creation process while maintaining control over your site's performance and security. By following the steps outlined in this tutorial, you'll be able to efficiently copy posts and preserve all the necessary data, ensuring a smooth and consistent workflow.

Written by:
James Mew
AI Automation Expert | former Head of eCommerce

With 20+ years in eCommerce and a proven history of scaling a 7-figure business, I know how to transform challenges into opportunities for growth. As the former Head of E-commerce for a European food tech company, I managed 14 e-shops across Europe and South Africa. Now, I specialise in helping professionals like you unlock the potential of AI automation for your business. 

Over 1,800 students have already enrolled in my online courses to master these skills. Whether you’re looking for hands-on AI automation services or want to upskill with my courses, I’m here to help. Connect with me on LinkedIn to discuss your needs or join my programs to start building smarter, more scalable systems today!

Related Posts

Smart ChatGPT Productivity Hacks for Business Professionals [Free Mini-Course]
CoursesProductivity

Boost your productivity with AI! Learn key ChatGPT productivity hacks in this FREE mini-course designed for freelancers, entrepreneurs, and business professionals. Master smart prompts, AI-powered workflows, and more to save time and streamline your tasks.


Read More »
Holy Sheet! Give Google Sheets Superpowers with These Add-ons
SoftwareProductivity

Looking for ways to supercharge your Google Sheets? Check out these amazing add-ons that can help you bring in data from your business or ecommerce store, automate tasks, analyze data, and create stunning visualizations.


Read More »
Guide to Email Marketing Campaigns: The Automated Growth Hack for Ecommerce Businesses
Email MarketingEcommerce

Learn how to create and implement email marketing funnels to automate your sales and grow your ecommerce business. This article show you all the best campaigns and sequences to run on your ecommerce store.


Read More »

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram