Purchased a new domain & hosting and looking for a quick guide on how to install WordPress in cPanel? Tutorials on the internet are time taking and not good for beginners? Then you are in the correct place. We will help you to install WordPress quickly and effective way you never forget.
WordPress is the most popular content management system in the world right now. WordPress now powers over 34% (as of May 2020) of overall websites on the internet. Everyone loves using WordPress because it’s easy and 1-click to build a website. You can install WordPress in a few clicks otherwise you can choose Bluehost Managed WordPress Hosting for a managed WordPress solution.
Most of the web hosting companies provide you with cPanel hosting which makes things easier for you. For that, you should understand how to install WordPress on Cpanel and take the benefits of cPanel.
In this tutorial, we will show you the complete step by step guide on WordPress installation. We will use Softaculous for WordPress self-hosted installation. It’s easier than manual WordPress installation, save a lot of time and reduce your headache.
So without wasting any more time, let’s begin!
cPanel is a Linux web hosting software which is used as a control panel to manage web hosting server and simplify website management, developed by cPanel L.L.C. It’s easy to use and you don’t have to require any technical knowledge on the command line or Linux utilities. cPanel helps you to manage/publish a website, manage domains, create emails, manage phpMyAdmin, install SSL and much more.
Take a look at it.
Most of the shared hosting plans have cPanel includes. If you are using shared hosting as a beginner, there will be a probability your host will use cPanel. Using Cpanel do can do the following things for WordPress sites:
Now let’s find out how to access your web host’s Cpanel.
So before we proceed and do anything, you need to find out how to access cPanel.
The easiest way to find the cPanel access details is, check your hosting provider’s welcome email after you signed up for hosting. The email contains all valuable login details and direct access URL to your cPanel.
If you didn’t find that welcome email, don’t worry. You can directly ask your hosting provider to send you again or go to your hosting account and find the Access cPanel or Login To cPanel button. It will automatically be logged in to access it.
You have cPanel login details but forget the cPanel URL to access it? Follow the steps given below.
If you are a Hostgator user like us, then you can access cPanel directly from your Hostgator account. To find out login to your Hostgator customer account and select your hosting package. There will direct link to access your cPanel. Below is a screenshot how it will look like.
So, now you got an idea about what is cPanel and how to log in there. You see there are lots of options and lots of things to do.
Relax. You don’t have to understand all about cPanel features and how it works. We are here to do one simple task – learn how to install WordPress in cPanel.
Let’s check out the tools cPanel provides you for installing WordPress automatically. Tools/scripts sections are usually located at the bottom of the page.
Depending on your hosting provider, your cPanel might be using any the following auto-installers: Softaculous, QuickInstall, Mojo Marketplace, or Fantastico.
For this tutorial, we will only focus on Softaculous since its the most popular auto-installer script and most of the hosts include it.
But don’t worry if your host uses any other auto-installer. The interface might be a bit different but the working principle behind every installer is the same. Soon we will write separate articles for each installer. Till then if you are facing any issue, do comment below. We will be there to help you.
To install WordPress in cPanel using Softaculous, login to your cPanel and look for it on software or WordPress Tools section. Or you can directly search it on the cPanel search bar.
Click on the Softaculous icon and it will launch Softaculous auto-installer for WordPress. There will be lots of options there, choose WordPress, and click on the Install tab to continue with the installation process.
Now Softaculous will ask you to provide some basic details to install WordPress for you. You should pay some attention here.
1. “Choose the version you want to install” – Always choose the latest available version. Google for the latest WordPress version.
2. “Choose Installation URL” – If you have multiple domains, select the domain where you want to install WordPress.
3. “Choose Protocol” – Choose http:// or http://www. as protocol. If your website has SSL and HTTPS, then you must select https:// or https://www. as protocol.
4. “In Directory” – Leave in directory field blank if you want to install WordPress in the domain’s root directory.
5. “Site Settings” – Provide a small title and description for your WordPress website. Don’t worry you can change everything from the WordPress admin section after installation complete.
6. “Admin Account” – Choose admin username, provide a strong password, and email address. Give proper email address otherwise you will face lots of issues later on.
7. “Choose Language” – Select your preferred language for your website.
Leave the rest of the options as it is. Now click on the Install button to proceed.
Softaculous will run the auto-installer with the settings you have provided. A progress bar with installation status will appear and it will take a few minutes.
After finish the installation you will see a confirmation message with WordPress login details. Check your email for WordPress admin username and password as well. You should note down the details in a safe place.
And that’s it. You have successfully installed WordPress using cPanel. You can access your newly installed WordPress website at yourdomain.com/wp-admin.
Heres a video guide on how you can install WordPress in cPanel.
We hope this quick guide on how to install WordPress in cPanel helped you to learn something new today. You can also check out the best hosting providers that the WP Recommend team highly suggests to you.
Leave a comment below if you find this article helpful anyway and let us know if you have any questions related to installing WordPress in cPanel. Don’t forget to share it on social media.
]]>Want to faster your website loading time, then you must try to defer parsing of Javascript. This is the most complicated issue which reduces your WordPress websites load time. It allows browsers to render the Javascript file only after the main content finished loading.
Whenever you are testing your site performance on free speed testing tools like GTMetrix, Google PageSpeed Insights, Google Test My Site, Pingdom or KeyCDN, it may suggest you to “Defer the parsing of Javascript”.
This can interrupt page load time and decrease the website speed to open. But you can defer this situation, so the browsers can load the website content first without waiting for javascript to load.
In this article, we will discuss 4 different methods on how to defer parsing of JavaScript in WordPress. We are going to explain what does defer parsing of Javascript means? And How can you easily implement this on your WordPress site easily. Let’s start!
Whenever visitors came to your site, it will tell their browsers to wait for Javascript to download until the main content already finished loading. So visitors can already see the content on your site and they don’t have to wait for the download and parse the Javascript.
Using some free and paid tool you can easily speed up your website and it helps you to rank better than any slow loading site. Google loves it and also gives you better visibility & ranking.
Yes. It really matters a lot for your site ranking and visibility. Google utilizes the website page speed as on the ranking factors, and it’s one of the major factors. Google measures the page speed when the page is initially loaded. That means your website pages must be load as quickly as possible.
The initial page load time means when the page loads completely without waiting to load content. Google actively updates their algorithms and recommend webmasters to get rid of resources like JS, CSS, etc or use minimal critical rendering paths.
If parsing javascript makes users happy and rank you better on google. You should apply the changes.
When any visitors visit your website, your website server delivers the HTML contents to the visitor’s browser. After HTML contents load complete, if it finds any Javascript, the loading process will stop until it finishes downloading all Javascript files.
To solve the issue you can defer parsing of Javascript in WordPress, which allows the browsers to load contents first without waiting for Javascript to load. It will negatively affect Javascript parsing to your website loading time.
Always keep in mind that having lots of Javascript isn’t bad for your site. It is one of the essential web components of a website to enhance site functionality. More importantly, you will get two main benefits:
To test if your WordPress website needs to defer parsing of Javascript, there are 20+ free website speed test tools available. Our recommendation will be GTmetrix to test with.
GTmetix will scan your complete webpage and generate a detailed report. It will give you a grade with performance and also some other specific points that need to be optimized. You can save the report for the future to see if your website is fastened enough after Defer Parsing of JavaScript.
There are many different ways to defer parsing of Javascript. First, add both attributes to your Javascript to clear it from the critical rendering path. Both attributes let users download Javascript without waiting for HTML parsing.
The difference between the two attributes are:
Async does not stop parsing HTML to fetch the script, it stopped the HTML parser to execute the script when it fetched completely.
Defer allows visitors browsers to download scripts while it parsing the HTML. But they have to wait to parse the script until the HTML parsing has been completed.
Growing With The Web created graphics that will explain the difference in short.
Another method they mentioned in the image is to simply move the Javascript file to the bottom of the webpage. But this method is not actually effective, because even it loads pages faster but visitors browsers still loading until the script loading completes. This can increase your bounce rate as visitors think content won’t be loaded fully.
To defer parsing of Javascript in WordPress, you have 3 options to choose from. Don’t worry we will show you step by step guide to defer parsing of Javascript and which method you should apply on your WordPress website.
Now let’s dig deeper to find out which will best for you.
The most effective way to defer Javascript parsing in WordPress using a plugin. There are many free and paid plugins available to simplify your task.
WP Rocket plugin includes inbuilt integration to fix the server level caching. Also, there is a bunch of other features available to optimize your website. It is really a handy tool to boost up your website speed.
Open the File Optimization tab in WP Rocket to defer the parsing of Javascript. Find the Load Javascript Deferred option and Enable it. To avoid site breakdown WP Rocket allows you to exclude JQuery.
Async JavaScript plugin is a free WordPress plugin that allows you to defer parsing JavaScript using either async or defer. Download and install the plugin to get started.
Navigate to Settings >> Enable Async JavaScript. As we mentioned earlier it allows you to choose between Async and Defer.
Like WP Rocket, Async Javascript also gives you the option to exclude jQuery scripts. This is a really great feature that may be broke your site’s core functionalities. So for safe, we recommend you exclude jQuery from deferring. Also, you can manually include or exclude any specific scripts from being deferred.
If you don’t want to use any plugin for it, simply edit your theme’s function.php file and add the below code snippets. Here’s how you can do it:
function defer_parsing_of_js( $url ) {
if ( is_user_logged_in() ) return $url; //don't break WP Admin
if ( FALSE === strpos( $url, '.js' ) ) return $url;
if ( strpos( $url, 'jquery.js' ) ) return $url;
return str_replace( ' src', ' defer src', $url );
}
add_filter( 'script_loader_tag', 'defer_parsing_of_js', 10 );
Finally, update and save the file.
This code snippet tells WordPress to defer all your Javascript files except jQuery. It’s quick and easy to add, right? But it doesn’t allow you to control or switch between Defer and Async.
Add this Varvy code snippet and add the script to your theme before closing </body> tag. Here’s the Varvy code:
<script type="text/javascript">
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "defer.js";
document.body.appendChild(element);
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>
Remember to replace the “defer.js” file with the actual file name/path of the Javascript file. Or you can use the wp_footer hook to inject the code to your theme’s function.php file. Finally, it will wrap like this:
/**
Defer parsing of JavaScript with code snippet from Varvy
*/
add_action( 'wp_footer', 'my_footer_scripts' );
function my_footer_scripts(){
?>
REPLACE_WITH_VARVY_SCRIPT
<?php
}
After following any of the methods you can test the changes, re-analyzing with GTmetrix.
Deferring the Javascript Parsing on WordPress is really important to improve your website performance. At the conclusion we must advise you to do the below steps:
Keep in mind that improving website loading speed will help you to rank better on Google than other sites and improve user experience.
If you still have questions in mind about how to defer parsing of Javascript in WordPress? Comment below and we will get back to you with a solution.
Don’t forget to check: Disable Directory Browsing in WordPress
]]>HTTPS stands for HyperText Transfer Protocol Secure, a protocol for secure communication between your website server and computer network.
Installed an SSL certificate for your website and your website still redirecting over HTTP? Don’t worry we are here to solve your issue on how to force HTTPS using .htaccess file.
After installing SSL your website is available in both HTTP and HTTPS versions. But we strongly recommend you to use only HTTPS version to encrypt and secure your server. Hosting providers allow you to force https over HTTP.
You may wonder why we should use HTTPS over HTTP. Nowadays website owners are preferring to use https and they are migrating from HTTP to HTTPS for the following reasons:
There are lots of options available for you to force HTTPS in WordPress. In this particular post, we will talk about how to redirect HTTP to HTTPS in WordPress using the .htaccess file.
You can redirect all your traffic via .htaccess file using 301 permanent redirects. Your all old URLs will be replaced with the new one automatically after applying the below steps:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Adding the above code in your website root folder, .htaccess file force HTTPS for your entire site. Let’s see how you can force SSL on a specific domain or subdirectory.
You can force HTTPS on a specific folder or subdirectories using .htaccess file. Make sure to create a new .htaccess file for that specific directory or folder which you want to make HTTPS enabled.
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(folder1|folder2|folder3) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Let’s say you want to secure “yourdomain.com/folder1” using .htaccess. All you have to do is create a new .htaccess file inside the “folder1” folder and put the code on it.
Let’s assume you have two different websites http://website1.com and http://website2.com, but both websites access the same website. Now you want to redirect HTTP to HTTPS on “website1.com” only. So what you have to do is, put the code on your .htaccess file for the specific domain.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^website1.com [NC]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Make sure to replace ‘website1.com’ to your actual domain name.
After applying all the changes clear your website cache and reload your website over HTTP. Magic right? It automatically redirects to HTTPS over HTTP.
Awesome, now you have redirected all your visitors to HTTPS from HTTP automatically. Visitors will see a secure icon before your domain name.
Depending on your website CMS (Content Management System), there will be some ways to enable SSL on your website. So your website can securely show you encrypted content over HTTPS.
Like, WordPress and Prestashop CMS use some plugin to enable that feature automatically and modify the .htaccess file to force HTTPS over HTTP.
Do you know any additional steps to force HTTPS using .htaccess file in WordPress? Share your thoughts on the comment section. Looking forward to your ideas, questions or suggestions.
Don’t forget to check How to Debug and Fix 503 Service Unavailable Error in WordPress.
]]>Run a WordPress blog is very easy nowadays but got an error is very irritating. In most cases, WordPress gives you some error log, by which you can get some clue how to fix the error. Troubleshooting the error log makes you a lot easier to fix that error. Unfortunately, 503 Service Unavailable error doesn’t give you so much information about the error.
Are you seeing a blank white screen with the error code ‘503 Service Unavailable‘ and not sure what to do? Don’t worry in this tutorials we will explain to you how to fix 503 service temporarily unavailable error.
The ‘HTTP 503 Service Unavailable Error’ is an HTTP status code which means your website is live but the server cannot be reached now. Most of the cases occur because the server is too busy to handle another job. Like server is under maintenance, updating or any particular reason.
A 503 error can be caused by many reasons. It can be customized by the website server it appears on or the server software which you are using that generates it.
Just like any other errors website developers can customize how to show a 503 error. So you might see different types of 503 service unavailable error pages on different websites.
For example here are some 503 error variations you might see depending on your browser and server configuration. Here is the most common errors:
This can be caused by many reasons. Using outdated themes or plugins or didn’t update WordPress core for a long can be an issue too. But don’t worry fixing HTTP 503 service unavailable isn’t that hard, we will make this easy for you.
Since you don’t have an idea of what caused the 503 error, you have to troubleshoot your site as instructed below. We have shared some best methods to find out the potential root causes and fix the 503 error.
After each step we recommend you to take a moment and check your website if the 503 error is gone. If the error is gone, ignore the remaining steps. Otherwise, try all the steps until you got the solution.
In most cases, 503 error causes because of incompatible WordPress plugin. If you encountered a 503 error after updating or installing a plugin, you may be found the culprit. Just delete the plugin from the Cpanel → File Manager to solve it quickly.
To determine if the plugins causing the errors you need to disable all of your plugins. This should diagnose the issue and give you some clue to fix it.
Due to the 503 error prevents you to access wp-admin dashboard area, you will need file manager access.
Do it via your hosting Cpanel → file manager and follow the below steps:
At Step 5 if you can see your 503 error has been solved then the plugins are the main culprit of this issue. Now you have to find which plugin causing the error, this may take a while if you are using a lot of plugins.
Now return to Step 6 and undo the changes. Then you have to manually check each plugin one by one until you can see the issue solved.
To do this you have to open wp-contents → plugins directory again and inside it, you will see all plugins are named as each folder. Follow the steps to check one by one:
All you have to do is delete the plugin from the plugins folder. Follow the above steps to access the public_html/wp-content/plugins folder.
Let’s assume the buggy plugin is WPS Hide Login. Just right click on the folder name and delete from the drop-down menu.
After performing all the above steps the 503 service unavailable should disappear and your site is fully functional. If still, the issue is the same move on the next step for troubleshooting.
If you tried the plugins that are not causing the 503 error, your WordPress theme might be a problem too. In most cases, after installing a new theme you can get HTTP 503 error because of compatibility issues.
To solve the issue you can switch back to default WordPress theme, like Twenty Sixteen, Twenty Seventeen or the latest Twenty Nineteen theme.
Unfortunately, the process as we stated above doesn’t work. WordPress won’t revert to its default theme if you simply rename the theme folder like before. This could end up with an error like:
If you wish to rename the entire theme directory as above, you could end up with an error like:
Deactivate WordPress theme through file manager is similar to disable plugin, but this time we will show you how to do it through the file manager. Basically, we want to give you an idea of how you can do it both ways. Let’s follow the steps:
Note: As we stated before your website frontend will come up with errors. But if the current theme has an issue above steps can give you access to your backend.
Can’t remember your currently using theme name? Don’t worry here what to do. Log in to phpMyAdmin to find the theme and deactivate it to revert the default theme.
If the 503 service unavailable error fixed by deactivating the current theme, it means there is some issue with your WordPress theme. You should upload the freshly updated theme or try reinstalling it or simply choose another theme.
Sometimes, 503 Service Temporarily Unavailable error comes due to your CDN provider. If you are using any content delivery network (CDN), a quick fix will be deactivating it temporarily.
CDN networks like Cloudflare, AWS, Google CDN, Incapsula, etc provided a separate panel to manage it. You can disable it by logging in to their account and give it a try if that’s work or not. Even your hosting Cpanel has an option for CDN, if you are are using Kinsta, Siteground or Hostgator. Just navigate and choose CDN → Disable CDN.
Each hosting provider has a different interface to enable and disable it. Most hosting platforms use Cloudflare free CDN, which causes a 503 error. If you are unable to disable CDN from Cpanel, you can ask your host provider to do it for you. Or you can check their knowledge base for more detailed information.
Still, have the issue? Don’t worry there are few more tweaks left to try. Don’t forget to reactivate your CDN if you have deactivated earlier.
Monitoring your servers error log regularly is a good practice. You can get lots of data about your website statistics even your website running fine. To define the faulty code doing the 503 error we have to enable debug mode.
Activate the WP_DEBUG mode from File Manager and check the error log. Here is how to step by step:
define ('WP_DEBUG', true);
define ('WP_DEBUG_LOG', true);
define ('WP_DEBUG_DISPLAY', false);
@ini_set ('display_errors', 0);
Now you can find the error log located at /public_html/error_log or /public_html/wp-content/debug.log. Open the file and see the recent logs.
We hope you got some error log to work with. Now simply follow the instructions and try to figure out what causing the 503 error.
If the HTTP 503 Service Unavailable Error displaying because of a broken PHP code, you can try to enable the PHP error log. But how to know which third party PHP codes are causing the error. That’s why we have to debug and diagnose it.
You just have to add the following code snippet to your wp-config.php file. You can check the stats on the console tab of Google Chrome DevTools.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Also, you might have to modify your php.ini file with the following code.
display_errors = on
If the above methods do not work for you, it could be a server-side error. We have added the solution to it. Let’s check them out.
Still, facing the 503 error despite all your attempts to fix so far? Then it will be a reason of due to lack of server resources. You can check google analytics if you are getting high volume traffic than usual.
However, you can still face a 503 error if you don’t have huge traffic than regular. It can be your server’s insufficient RAM problem too.
We suggest, upgrade your hosting package if the current hosting plan can’t handle all the resources of your website. So the best practice is to first contact your current hosting provider customer support team and discuss the issue with them. They will figure out the issue and solve it for you. The support team will help you to advise whether you need to upgrade your hosting plan or not. Bluehost is our only recommendation.
WordPress Heartbeat API is an inbuilt API from WordPress, which allows your website some cool features. Like, autosave the content, alert you when someone is editing the content, show you a realtime notification, etc.
WordPress Heartbeat feature works in the background and consumes your server’s resources, but you have the option to limit or disable it with Heartbeat Control WordPress plugin. Usually, that isn’t a problem but in some cases, it cay cause you 503 service unavailable error.
The fastest way to do it via Heartbeat Control WordPress plugin. Navigate to settings → Heartbeat control section and modify the frequency number lower.
To determine the error caused by the WordPress Heartbeat function on your website manually, you have to put some code. Locate the public_html → wp-content → themes folder → choose the current theme and open the functions.php file in edit mode. Add the following code after opening <?php tag:
add_action('init', 'stop_heartbeat', 1);
function stop_heartbeat(){
wp_deregister_script('heartbeat');
}
Now save the changes and refresh your website to see if the error has disappeared or not. If this didn’t fix the WordPress 503 error, then it might not be the root cause of the problem. So, you can remove the code from functions.php file.
If all the above 6 steps didn’t help you at all, you have only one option left to give it a try.
Sometimes the 503 error will only show for a few moments when the website server is in maintenance mode and resolved automatically. Most of the cases it happens due to PHP code error. However, when you don’t get any clue about the error its time to do more troubleshooting or contact your hosting support team.
To solve the 503 service unavailable error, you need to follow the steps:
Do you have faced the HTTP 503 WordPress Error? Share your experiences with us on how you fixed the error in the comment section!
Don’t forget to check how to duplicate WordPress page or post.
]]>Sometimes we want to take a backup of our currently working on WordPress post or page. And it’s a good habit when you are working on a really important project. Duplicate WordPress page or post with a single click can save you lots of effort and time.
Duplicate post or page allows you to take a backup of your existing work as a template, which you can use for future preferences. In this article, we will explain to you how to duplicate a WordPress page or post with and without plugins.
There are lots of ways to do clone a post or page in WordPress. We will cover all of them. Without any wasting time, let’s jump into it.
The easiest way to duplicate a WordPress page or post by using a plugin. There are lots of free plugins available at the WordPress plugin library. You just need to install and activate the plugin. After activation duplicating a page or post is a 1-click away.
Let’s take a look at which plugins can make this job easier for you. We will discuss the best WordPress plugin to duplicate posts or pages as well as how to use them shortly.
Duplicate page WordPress plugin is the best plugin we have ever used. You can duplicate WordPress page, post and custom post with a single click and it will save as your preferred options (draft, pending, private or public).
Duplicate Page Pro edition gives you more freedom like:
To clone your WordPress posts or pages using Duplicate Page plugin, follow these simple steps:
The powerful Duplicate post WordPress plugin allows you to duplicate not only content (post and pages), it also duplicates comments, menu orders, slugs, etc for future use.
Like duplicate page pro plugin, it allows you almost all freedoms. You can add prefix or suffix to the post and pages. So it became easier for you to remember which is a clone and which is original.
For example, you want to set ‘Clone Of’ as the title prefix for each clone post/page. Now if you duplicate a post named ‘What is SEO?’, the clone will be named “Clone of What is SEO?”.
To duplicate WordPress page or post using Duplicate Post plugin, follow these simple steps:
For more help, you can refer to its documentation site: Duplicate post plugin documentation.
Post Duplicator plugin allows you to create an exact copy of posts or pages while it retains all custom taxonomies and custom fields as well. Custom post types are also supported.
Let’s check how to duplicate a WordPress page or post using Post Duplicator plugin:
You can customize the plugin settings if you wish. Go to Tools > Post Duplicator and set the post status (draft, same as the original or published), post date and post type.
Apart from using regular WordPress plugins, you also have a choice to make some tweak on coding to duplicate posts or pages. Coding geeks will love this method.
You just need to put the below code snippet to your functions.php file. Login to your Cpanel file manager, FTP or you can do it via inbuilt WordPress file manager.
Code snippet for duplicate WordPress post
/*
* Function for post duplication. Dups appear as drafts. User is redirected to the edit screen
*/
function rd_duplicate_post_as_draft(){
global $wpdb;
if (! ( isset( $_GET['post']) || isset( $_POST['post']) || ( isset($_REQUEST['action']) && 'rd_duplicate_post_as_draft' == $_REQUEST['action'] ) ) ) {
wp_die('No post to duplicate has been supplied!');
}
/*
* Nonce verification
*/
if ( !isset( $_GET['duplicate_nonce'] ) || !wp_verify_nonce( $_GET['duplicate_nonce'], basename( __FILE__ ) ) )
return;
/*
* get the original post id
*/
$post_id = (isset($_GET['post']) ? absint( $_GET['post'] ) : absint( $_POST['post'] ) );
/*
* and all the original post data then
*/
$post = get_post( $post_id );
/*
* if you don't want current user to be the new post author,
* then change next couple of lines to this: $new_post_author = $post->post_author;
*/
$current_user = wp_get_current_user();
$new_post_author = $current_user->ID;
/*
* if post data exists, create the post duplicate
*/
if (isset( $post ) && $post != null) {
/*
* new post data array
*/
$args = array(
'comment_status' => $post->comment_status,
'ping_status' => $post->ping_status,
'post_author' => $new_post_author,
'post_content' => $post->post_content,
'post_excerpt' => $post->post_excerpt,
'post_name' => $post->post_name,
'post_parent' => $post->post_parent,
'post_password' => $post->post_password,
'post_status' => 'draft',
'post_title' => $post->post_title,
'post_type' => $post->post_type,
'to_ping' => $post->to_ping,
'menu_order' => $post->menu_order
);
/*
* insert the post by wp_insert_post() function
*/
$new_post_id = wp_insert_post( $args );
/*
* get all current post terms ad set them to the new post draft
*/
$taxonomies = get_object_taxonomies($post->post_type); // returns array of taxonomy names for post type, ex array("category", "post_tag");
foreach ($taxonomies as $taxonomy) {
$post_terms = wp_get_object_terms($post_id, $taxonomy, array('fields' => 'slugs'));
wp_set_object_terms($new_post_id, $post_terms, $taxonomy, false);
}
/*
* duplicate all post meta just in two SQL queries
*/
$post_meta_infos = $wpdb->get_results("SELECT meta_key, meta_value FROM $wpdb->postmeta WHERE post_id=$post_id");
if (count($post_meta_infos)!=0) {
$sql_query = "INSERT INTO $wpdb->postmeta (post_id, meta_key, meta_value) ";
foreach ($post_meta_infos as $meta_info) {
$meta_key = $meta_info->meta_key;
if( $meta_key == '_wp_old_slug' ) continue;
$meta_value = addslashes($meta_info->meta_value);
$sql_query_sel[]= "SELECT $new_post_id, '$meta_key', '$meta_value'";
}
$sql_query.= implode(" UNION ALL ", $sql_query_sel);
$wpdb->query($sql_query);
}
/*
* finally, redirect to the edit post screen for the new draft
*/
wp_redirect( admin_url( 'post.php?action=edit&post=' . $new_post_id ) );
exit;
} else {
wp_die('Post creation failed, could not find original post: ' . $post_id);
}
}
add_action( 'admin_action_rd_duplicate_post_as_draft', 'rd_duplicate_post_as_draft' );
/*
* Add the duplicate link to action list for post_row_actions
*/
function rd_duplicate_post_link( $actions, $post ) {
if (current_user_can('edit_posts')) {
$actions['duplicate'] = '<a href="' . wp_nonce_url('admin.php?action=rd_duplicate_post_as_draft&post=' . $post->ID, basename(__FILE__), 'duplicate_nonce' ) . '" title="Duplicate this item" rel="permalink">Duplicate</a>';
}
return $actions;
}
add_filter( 'post_row_actions', 'rd_duplicate_post_link', 10, 2 );
This above code snippet only works for duplicating WordPress posts. You can duplicate WordPress pages by changing the last line with this code:
add_filter('page_row_actions', 'rd_duplicate_post_link', 10, 2);
Don’t have access to FTP or Cpanel? Don’t worry. Navigate to Appearance > Theme Editor, and select Theme Functions.
Now, if you have successfully added the code to your functions.php file, you should see a Duplicate button in All Posts or All Pages.
We hope in this tutorials we have covered up all tips & tricks on how to duplicate WordPress page or post with or without plugins. Let’s recap the summary:
With Plugins: You can duplicate or clone WordPress posts or pages easily. For this, you have so many plugins available like Duplicate Page, Duplicate Post or Post Duplicator plugin.
Without Plugins: If you are an expert at coding then you can try this. Just edit the function.php file with the above code and done.
Do you know any other way to do that? Share in the comment section so everybody can use that method too. Anyway if you have any questions you can ask at comment or contact us. Meanwhile, you can check out other tutorials.
]]>