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
Selljam Founder | Head of eCommerce

With over 20 years of experience in the eCommerce world, I’m a 7-figure business expert, having launched and scaled multiple successful online businesses. In 2022, I took on the role of Head of E-commerce for a European food tech company, managing 14 e-shops across Europe and South Africa. Today, through Selljam, I share AI-driven strategies and eCommerce hacks to help business professionals like you achieve success. Over 750+ students to date have already enrolled in my online courses, and I’m excited to help you take the next step toward building the online business of your dreams!

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 »
Professional Productivity Hacks: Unlock Your 10-Hour Advantage
CoursesProductivity

Learn How to Optimize Task Management, Enhance Focus, and Leverage AI for an Unbeatable Advantage to Unlock Peak Performance


Read More »
Week 5 Update: How to Create an Online Course and Earn $1,100+ Per Month - Camtasia Templates & iPhone Webcam App
ChallengesOnline Course Challenge

This week, I focused on creating a Camtasia template for efficient video editing and batch recording all lessons for Section 1. I completed key productivity topics, tested iVCam for high-quality video recordings, and recorded numerous lessons in Sections 2 and 3, covering productivity strategies and tools like Phrase Express, Trello, ClickUp, and Airtable. Discover my streamlined workflow and progress in enhancing my course content.


Read More »
Week 4 Update: How to Create an Online Course and Earn $1,100+ Per Month - Editing Workflow Optimisation
ChallengesOnline Course Challenge

Discover how I advanced my course creation this week with completed lesson preparations, detailed automation diagrams, main lesson recordings, systematic backups, and optimized editing workflows, setting the stage for efficient and engaging content delivery


Read More »
Week 3 Update: How to Create an Online Course and Earn $1,100+ Per Month - Camtasia, B-roll clips & ChatGPT Book Summaries
ChallengesOnline Course Challenge

Kicked off by creating the Snagit demo video, highlighting its screen capture and recording capabilities. Planned upcoming demos for Lipsurf, Gmelius, Zapier, Make, and GPT for Sheets. Recorded the "Gmail: Priority Star Method" lesson.


Read More »
Week 2 Update: How to Create an Online Course and Earn $1,100+ Per Month - Automation Mini-Projects and Software Demo Lessons
ChallengesOnline Course Challenge

Kickstarted course creation with Zapier and Make tutorials, completed software demos, set up custom tools, and finished all lesson scripting for next week's filming.


Read More »
Week 1 Update: How to Create an Online Course and Earn $1,100+ Per Month - Custom GPTs & Scripting Lessons
Online Course ChallengeChallenges

Despite my experience in eCommerce, I’ve never created an online course before. This is my first time, and I’m a bit nervous about it. But that’s what makes this challenge so exciting! I’m here to learn, grow, and hopefully inspire you along the way.


Read More »
Exploring Subdomain vs Subdirectory vs CCTLDs: Choosing the Right Domain Structure for SEO Success
SEOEcommerceGuides

Discover the 13 key factors for choosing the right domain structure that will ensure SEO success. Learn the pros and cons of subdomains, subdirectories, and CCTLDs to choose the best option for your website's SEO and improve your website traffic.


Read More »
Google’s Product Evolution: A Timeline Of App Name Changes
Technology

Google has been constantly evolving its product names over the years. Some of these changes have been minor, while others have been more significant. Let's explore these name changes and some of the reasons behind them.


Read More »
Customer Identity Verification Tools: The Best Apps to Protect Your Ecommerce Store
Ecommerce

When secure card payments aren't enough and you need an extra layer of protection, then customer ID verification may be just what your business needs to level up. Comply with regulations and also protect your ecommerce business or app from fraud and chargebacks with the best customer identity verification tools.


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 »
1 2 3 4

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