23 Most Useful Wordpress Code Snippets For Performance, Seo And Security

23 BEST WordPress Code Snippets for Speed, SEO, & Security

Home > Creations > 23 BEST WordPress Code Snippets for Speed, SEO, & Security

Aditya AgarwalLast Seen: Nov 25, 2023 @ 6:35am 6NovUTC
Aditya Agarwal
@AkarshitMahajan6300

So, you need some powerful, Useful WordPress Code Snippets that can help with SEO, Performance, and Security? Say no more; we have got you covered with some great, small, and efficient code that is Extremely Useful and can help reduce the plugin burden on your WordPress Site.

WordPress is a compelling platform, and the best part of WordPress is the ability to customize anything and everything based on your needs. I have brought you 23 of the most useful WordPress code snippets to improve SEO, performance, and Security. While plugins are excellent and can do a lot of work, plugins can slow you down, and many times, plugins cause conflicts. Ask any WordPress Plugin Author about an error in their Plugin. They first tell you to check whether any other plugin is not troubling.

Moreover, sometimes you need just a tiny feature and must install a big fat plugin. It’s like using a Sword for the work, which just a Knife can do. So here I bring you 23 Great WordPress Code Snippets to Improve SEO, Performance, and Security. You do not need to Worry, even if you do not know how to code; I will first help you create your Plugin in your WordPress Installation, so don’t worry.

0) Create Your Plugin

You put most of the code in your custom plugin, so creating a plugin as a Starting is better. Though not all the code is in Plugin, some code (especially Security ones), so let’s make a Plugin, but how to do that?

In your Hosting provider, GoDaddy, or whatever, you shall have FTP somewhere in your Hosting; FTP or File Transfer Protocol is what we use to manage files on the server and create a plugin.

While “manage files on server” gives goosebumps to many, I can tell you that everything would be safe, granted that you restrict yourself to the relevant Folder discussed later.

So, to manage files, you need some place to edit/access them. If you are using a Good Hosting provider, like Bluehost or Siteground, it won’t be a trouble. They have their File Managers; you must log in to the Hosting provider, go to your Site, and find the File Manager.

A file manager is essential. We do not recommend using the WordPress plugin to edit files, as all of them are fragile. To use our 23 code snippets for WooCommerce and WordPress Performance, SEO, and Security, you need to have a Hosting File Manager or a 3rd Party FTP. FTP stands for File Transfer Protocol

If your provider does not give direct File Editor, they give you the FTP details directly; you can generate your credentials. FTP runs on PORT 21, and SFTP runs on port 22. Port 22 is relatively secure. Therefore, it is possible to use that. So now you need some application through which you can log in to FTP.

I recommend WinSCP for Windows and FileZilla for other platforms. Once you have downloaded it, you can add a new site and fill in the details you generated with the above method.

So once you are in, you shall have a File Manager on your server just like you have files for your PC. You should be greeted by a Folder with your site name or a folder saying “public_html.”

Below is the destination you should reach; some file managers omit the initial locations, but after public_html, it’s mostly the same.

{domain_name}/public_html/

Now, we are ready to get onto developing. To save you time and be helpful, we divided our snippets into parts, beginning with Speed, then going onto SEO, and many other things.

In this directory, you would have a lot of folders. Each Folder represents One Plugin. So, as it might be obvious, let’s create a plugin for you.

So, decide the name for your excellent Plugin; for the sake of this article, I shall assume the name to be “Hello-Plugin.” So, create a folder with your plugin name.

Then open that Folder. As expected, it shall be empty. If you refresh the plugins page in wp-admin, you won’t see this Plugin because we have another step.

Again, in the plugin folder, we just created. It is your file manager should be empty. Create a file in it. You can name it almost anything, but it is good to call it the same as your plugin name. For best practice, it should have the file extension “.php,” meaning it should look like “Hello-Plugin.php.”

Now, once you create the file, open this file. From here, the portion starts with the actual code. So, be a lie; if anything goes wrong, be careful. However, I shall explain what to do if anything goes wrong.

So, into the file, type the code given below. It describes the Plugin Name, Author, Description, etc. Only the Plugin Name is compulsory, but I suggest keeping the Author, Description, and Version. Rest all can be erased. 

Now refresh your wp-admin page, and you will see your Plugin. Click the activate button and woohoo! You’ve created your first-ever Plugin.

First, open wp-config.php; if something goes wrong, copy the text in this file and keep it safe locally. In case of trouble, rename the plugin folder we created to anything random to deactivate it and bring the wp-config file to the original version.

23 Most Useful WordPress Code Snippets For Seo, Performance And Security Sample Plugin 

Useful WordPress Code Snippets

Using too many plugins for every #WordPress site can be troublesome, generate conflicts, and be slow. As a result, always use custom #CodeSnippet, as they do not execute extra code, which is useless for you. Now you are into your File Manager, and we shall start with various things to increase Speed.

I have compiled the list of these 23 Code Snippets; all of t#Secure, #Fast, and Simple simultaneously tried to add comments everywhere to explain the code so that the 23 most useful WordPress Code Snippets are easy to configure, and even if you are not a coder, you can use them.

To see the Plugin/3rd Party service-based Implementation for Improving WordPress Performance, refer to this article: How I Optimized my WordPress Website. In case you are not happy, you can always look into switching to top WordPress alternatives.

1) Leverage Browser Caching

Now, this one is perfect; all Modern Browsers support caching. Caching can serve the resources frequently loaded on your Site directly from a browser rather than downloading from the server. 

The critical thing to note is that you should preferably not use the Hosting’s File Manager, as that may not show hidden files. So try using WinSCP or FileZilla on your PC or Mac for this.

So, now navigate to “public_html/.htaccess.” This is called the ht-access file. This file is responsible for Server Configuration. Most Servers run on APACHE. So, below is the code for your htaccess file. Paste it at the bottom of the file.

You can find plenty of WordPress plugins to implement it, but as it turns out, this is the most efficient way, and I believe simple copy-pasting like this is something everyone can do. Again, if you have any problem, I am always available in the Comment Section below.

Also, updating this file can often cause some weird things to happen on-site. As a result, whenever you update the htaccess file, you should go to wp-admin -> Settings -> Permalinks and click “Save Changes” as a best practice.

  ExpiresActive On

  # Images
  ExpiresByType image/jpeg "access plus 1 year"
  ExpiresByType image/gif "access plus 1 year"
  ExpiresByType image/png "access plus 1 year"
  ExpiresByType image/webp "access plus 1 year"
  ExpiresByType image/svg+xml "access plus 1 year"
  ExpiresByType image/x-icon "access plus 1 year"

  # Video
  ExpiresByType video/mp4 "access plus 1 year"
  ExpiresByType video/mpeg "access plus 1 year"

  # CSS, JavaScript
  ExpiresByType text/css "access plus 1 month"
  ExpiresByType text/javascript "access plus 1 month"
  ExpiresByType application/javascript "access plus 1 month"

  # Others
  ExpiresByType application/pdf "access plus 1 month"
  ExpiresByType application/x-shockwave-flash "access plus 1 month"

2) Biggest Blunder jQuery Migrate

Remember the Plugin we created in Point 0. Let’s get back to it. WordPress brought jQuery Migrate, a JS file to bridge old jQuery files with new ones. It is helpful for people with old jQuery code incompatible with more recent jQuery.

But here’s the thing: the #jQuery Migrate is for compatibility of jQuery before 2012, and the vast majority of us would not have those old sites, and I believe the ones who have would have already re-coded for new jQuery directly.

So, most people with sites newer than 2012 (WordPress 3.6) do not need the jQuery Migrate library. Therefore, removing jQuery Migrate from WordPress on the front end is better.

Get into the WordPress Plugin we created. In it, you shall find a line as below.

//Your Future Code Goes Here

Now, you must add whatever code you want by replacing the above line with your code. So now here’s the code for dequeuing (Dequeue is the WordPress-ish term for removing JavaScript files ):

function deregister_qjuery() { 
 if ( !is_admin() ) {
 wp_deregister_script('jquery-migrate');
 }
} 
add_action('wp_enqueue_scripts', 'deregister_jquery');

 

Let me explain the above function to you. The above part goes through this function and runs whenever the wp_enque_scripts action happens. The wp_enqueue_scipts is responsible for attaching all javascript files on the #frontend.

So we then check if it is an admin page or not. Admin page is any page having wp-admin in its URL. So, if it isn’t an admin page, we deregister jQuery Migrate so it doesn’t get attached to the webpage.

I always do it in any of the sites I design; it’s useless for all modern areas.

3) WordPress Code Snippet to Prevent Hotlinking

Imagine you bought a cake for your son’s birthday and put it at your friend’s home to surprise your kids. When you open it, your friend has eaten half of it. You would feel bad, right? You spent money, but he got the reward. That’s the same on the Internet.

Your server has finite resources, and some clever people can try to load images on the Internet on your server for their Site. This means that some other site is loading images from your Site, meaning that your server resources are consumed for their benefit. Bad right?

That’s called Hotlinking, and it should be stopped. For most sites, only your Site can load images from your servers. And your resources are exclusive. Moreover, it is suitable for Security also. As you may want pictures to not

Here’s the code to do the same: insert it into the htaccess file.

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?google.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?bing.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yahoo.com [NC]
RewriteRule \.(jpg|jpeg|png|gif|svg)$ http://dropbox.com/hotlink-placeholder.jpg [NC,R,L]

4) Remove Dashicons from Frontend

Dashicon is an icon font used by WordPress; the icons you see in wp-admin are built through it. But usually, they are rarely used in front. Most of the plugins nowadays either use Favicons or their own custom Icon Font. As a result, we should not waste time optimizing for something that would have close to 0 impact on the front end.

So below is the code for the same. It would be best if you pasted this into your custom WordPress Plugin. This is a great way to improve your WordPress site loading time.

function wpdocs_dequeue_dashicon() {
        if (current_user_can( 'update_core' )) {
            return;
        }
        wp_deregister_style('dashicons');
}
add_action( 'wp_enqueue_scripts', 'wpdocs_dequeue_dashicon' );

5. Use Gzip Compression

gZip is powerful; it can compress and reduce the size of your webpage, meaning less time to load. It works like magic, though, for the need to wander through your file system.

It is based on this magic on your Hosting Provider, the php.ini file.

This file configures how #PHP and its extensions work on your server.

Be extremely careful with your file.

then most probably, it would have the following line in your file

zlib.output_compression = Off

 Please turn it on to turn on gZip compression.

gZip is one of the most essential WordPress Code Snippets. It’s a thing that should be standard and turned on by default, but still, it isn’t, regardless of it. Please use gZip. If you aren’t going to turn on gZip, sorry, we can’t be friends.

6) Limit Revisions

You must know that WordPress uses an Autosave functionality and saves your content while writing it in the backend.

Unfortunately, this content is saved as separate posts; in my case, I have had some posts with over 350 revisions, which meant that for a single post, WordPress had done 350 autosaves. And most of them were useless to me. And they slow down the Site. While Autosave can be helpful, I suggest limiting it to 20. This is a Useful WordPress #Code Snippet for optimization, but you should forget if you have fewer posts or if more occasional posts exist almost every time.

Opening the wp-config.php file (domain.com/public_html/wp-config.php), you shall scroll down to the bottom and find the line where it is written.

/* That's all, stop editing! Happy blogging. */
Add a line above it, and write the below code,
define('WP_POST_REVISIONS', 20);

It should collectively be like:

define('WP_POST_REVISIONS', 20);
/* That's all, stop editing! Happy blogging. */

As you can see, the line you added has the number “20” in it. WordPress would maintain the latest 20 Revisions and delete everything before them. You can adjust it to more or less. I frequently forget to save, so 20 is good for me; if you are more careful than me, then 5-10 can work for you. Adjust it based on your needs.

 

7) Limit Trash

Limit Trash is essential. If you don’t like Trash in your home, you should also not like Trash in WordPress. WordPress can keep debris for months without anything changing. Therefore, as a Best Practice, you should ensure that your Site doesn’t get choked due to deleted posts in your Trash. This is one of the 23 most useful WordPress Code Snippets for Speed, SEO, and Security, but if you are careless, you should use it for 15 days.

Currently, WordPress retains Trash for 30 Days, and it should be fine for most people, but if you have Trash, you need to delete it more frequently. To do that, go to public_html/wp-config.php and edit the file. 

Add the code below there. 

define('EMPTY_TRASH_DAYS', 7);

8) Disable Heartbeat API

Heartbeat API is a WordPress API that can interact with the server continuously without needing a page to reload. It is powerful, but this also means this API keeps sending server requests constantly, which keeps the server under pressure every time. The best way to tackle it is to turn off the Heartbeat API.

You can do it easily by wibydding the code below to the Plugin built earlier. 

Warning: This is an Important WordPress Code Snippet for speed, in some sites I have seen over 1 second saved in loading time by turning it off, but many sites need it. It largely depends on what themes and plugins you use. This Wonderful WordPress Code Snippet for Speed can break your site, or may break some features of it, test your site thoroughly, and if things don’t work with this snippet, then don’t use it.

add_action( 'init', 'stop_heartbeat', 1 );
function stop_heartbeat() {
wp_deregister_script('heartbeat');
}

If you feel we have done too much optimization, then sure, I shall let you go to SEO. SEO is as crucial as Speed and Security for sites. A tiny love a place with SEO in mind ought. Sometimes SEO can be time-consuming, like in the case of Image ALT tags, and sometimes it can slow down the site, like in the case of Sitemap plugins; I shall give you some secret recipes for doing it all.

I have worked hard to compile the list of these WordPress Code Snippets for SEO, and I hope these things help you get more views from Google.

9) Sitemaps

Sitemaps are essential for every Site. Sitemaps make navigation easy, and when submitted to Google, they simplify indexing and ranking your Site on Search Engines. There are many plugins in the WordPress directory which can create sitemaps with ease. The problem with them is that they slow down your Site. This is because some reindex your Site daily to find any changes. This is slow.

We know that the #Sitemap Plugins offered in WordPress are notoriously slow and are unnecessarily big. As a result, this Useful WordPress code Snippet is there to rescue you.

Instead, I found some code on the Internet, and with some improvisation of my own, I shall give you a code to make an update sitemInternetver a post is published/updated/saved.

So here are the steps. First of all, go to your Plugin. public_html/wp-content/plugins/Hello-Plugin/Hello-Plugin.php 

There, add the line below and save it.

include( plugin_dir_path( __FILE__ ) .'sitemap.php');

Now save the file called “sitemap.php” in your Hello-Plugin folder before proceeding; it’s better to check that your site is fine. Just open your Site, ensure things are fine, and do the next step.

So, the next step is to build the actual sitemap.

You need to copy-paste the code below in your sitemap.php, nothing else. It is also compatible with WooCommerce, so your WooCommerce products get added to it by default. It shall make a sitemap of all posts ordered by the last modified descending. 

 

add_action( 'publish_post', 'Sitemap' );
add_action( 'publish_page', 'Sitemap' ); 
add_action( 'save_post', 'Sitemap' ); 

function Sitemap() { 
$postsForSitemap = get_posts(
array( 'numberposts' =>-1,
 'orderby' => 'modified',
 // 'custom_post' should be replaced with your own Custom Post Type (one or many) 
'post_type' => array( 'post', 'page', 'download', 'product'),
 'order' => 'DESC' ));
 $sitemap = '';
 $sitemap .= ''; 
foreach( $postsForSitemap as $post ) { 
setup_postdata( $post ); 
$postdate = explode( " ", $post->post_modified ); 
$sitemap .= ''. '' . get_permalink( $post->ID ) . '' . '' . 
$postdate[0] . '' . 'weekly' . ''; } 
$sitemap .= ''; 
$fp = fopen( ABSPATH . 'sitemap.xml', 'w' ); 
fwrite( $fp, $sitemap );
 fclose( $fp );
 }

 

After that, the last step is to o; the previous step is to click the save button. As it is generated every time a post is saved/updated/published., your sitemap would be there on https://{yoursite. Com}/sitemap.XML


23 Most Useful WordPress Code Snippets For Seo, Performance And Security Sitemaps

10) Automated Image SEO

Images are immensely Important. Optimizing images to rank quickly on Google is equally necessary. We all know that there are some WordPress-specific Image Text fields, such as Captions, and some SEO-particular fields, such as Alt Text. Everyone should utilize them on their Site as it can be beneficial.

But in most cases, we are too lazy to type it in. Therefore, it’s better to have little automation. I built a code for you guys who can make your life easy. This code will extract the file name from the uploaded image and set the Alt-Text, Caption, Description, and Title as this very text. 

Say you are uploading an image of a person sitting with a laptop. Then name your image “Person Sitting with a Laptop.jpg,” the code will automatically set the Alt Text, Caption, Description, and Title as “Person Sitting with a Laptop.”

This means you must upload a file with a name that suits it. People usually upload files with random filenames or “images.png,” which would be wrong in this case, and in general, the URL of your image is developed from the filename. Therefore, a well-named Image is always better.

This is not only useful but also a time-saving WordPress code snippet.

So here’s the code:

add_action( 'add_attachment', 'my_set_image_meta_upon_image_upload' );

function my_set_image_meta_upon_image_upload( $post_ID ) {
// Check if uploaded file is an image, else do nothing
if ( wp_attachment_is_image( $post_ID ) ) {
$my_image_title = get_post( $post_ID )->post_title;

		// Sanitize the title: remove hyphens, underscores & extra
		// spaces:
		$my_image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ',
		$my_image_title 
	);
	// Sanitize the title: capitalize first letter of every word
	// (other letters lower case):
	$my_image_title = ucwords( strtolower( $my_image_title ) );
	// Create an array with the image meta (Title, Caption,
	// Description) to be updated
	// Note: comment out the Excerpt/Caption or Content/Description
	// lines if not needed
	$my_image_meta = array(
	// Specify the image (ID) to be updated
		'ID' => $post_ID,
		// Set image Title to sanitized title
		'post_title' => $my_image_title,
		// Set image Caption (Excerpt) to sanitized title
		'post_excerpt' => $my_image_title,
		// Set image Description (Content) to sanitized title
		'post_content' => $my_image_title,
		);
	// Set the image Alt-Text
	update_post_meta( $post_ID, '_wp_attachment_image_alt',
	$my_image_title );
	// Set the image meta (e.g. Title, Excerpt, Content)
	wp_update_post( $my_image_meta );
	}
}

?>

11) Automated Meta Description

Meta Description is one of the most essential things in the SEO world. Meta Description is what decides the conversion rate. Meta Description is what improved your conversion rate.

The first 100 words of your post are the most important thing after the Title/Content itself. If these 100 words are good enough, then it is b to extract the first few words from them as Meta Description.

I have also added an option that checks for excerpts. So, if your post has an excerpt, we would use that Excerpt as the meta description. If it does not have an excerpt, then we use the first 175 characters of your post to make it happen.

Meta Descriptions are critical, and WordPress does not have a direct way to add Meta Descriptions, which sometimes makes me feel bad.

Therefore, I built this code; you probably won’t need an SEO plugin after this. Just edit the Excerpt, and my Useful Code Snippet shall also convert it into a Meta Description.

function Head(){
	if (!is_page() &&is_single()) {   
		if (!is_singular() ) {return; 
		}
		elseif (!empty( $post->post_excerpt)) {
			$meta = $post->post_excerpt ;
			echo ''; 
			echo '';
			echo '';
		} 
		else {
			$meta = apply_filters('the_content', $post->post_content); 
			$meta = strip_tags($meta); 
			$meta = strip_shortcodes($meta );$meta = strip_tags($meta);
			$meta = strip_shortcodes($meta );
			$meta = str_replace(array("\n", "\r", "\t"), ' ', $meta);
			$meta = substr($meta, 0, 175);
			echo ''; 
			echo '';
			echo '';
		}
	}
}
add_action('wp_head', 'Head');

12) Table of Content using Headings

Table Of Contents is essential. At the start of the post, having a Table of Contents helps make things more transparent. It sets the town and the agenda of what will be covered in the center. Besides that, Table of Contents means that each heading would have its ID, and Google would recommend going directly to a Heading in search snippets.

It would look something like this.

So, the Table of Contents is Important. While there are many plugins for it in the market, they are slow. There are some JS-based alternatives, but they render after page load, meaning that they don’t impact SEO. Therefore, the method below is the best. I took this code from a Stack Overflow answer. StackOverflow Answer: Table of Contents with a shortcode

Full Credit to the original Creator of this code. In case you own any code and want it removed from this article, there is a “Report Content button” that shall help you.

23 Most Useful WordPress Code Snippets For Seo, Performance And Security Table Of Content

13) Breadcrumbs

We all remember Breadcrumbs from Hansel and Gretel, how they left Breadcrumbs to hint at the actual reaction. The same is true with the Web; we need breadcrumbs to tell Hierarchy, and Bryou is on the site on the Site you are.

For example, if you are on yousite.com/blog/blog-post, then you should have a Breadcrumb, which is a text like “yoursite.com  | Blog | Blog-Post”

Clicking Youtsite should take you to the homepage; the Blog should take you to the blog page, and so on.

Warning: This is a rob that dress code, but it needs some editing on your end; it works perfectly on my Site, but you must edit code here and there to make this great WordPress code snippet work correctly.


14) Social Media Sharing Buttons

Social Media is important, and so is sharing. The easiest way to get more people to read your articles is to have content that people share on social media. More often than not, people need 10 seconds to copy the link and share the content.

It’s, therefore, better for you to give them a button to easily share the content on Social Media platforms without any hassle. I have built a code that does the same.

It has four buttons: Facebook, Twitter, Google Plus, and Linkedin. Clicking them takes you to their respective sites, with the link of your post, so a person can click the button and directly share the link of your position on any of these platforms.

You need to put the given code in a plugin, and then later, wherever you want the buttons to appear, you need to set [Milyin_Share] to output the controls in your post.

This WordPress Code Snippet runs on the WordPress Shortcodes. It adds a Shortcode to your Site. 

The code is :

function Milyin_Share(){
$Link = get_permalink(get_the_ID());
$Title = get_the_title();

return '
';
}
add_shortcode('Milyin_Share', 'Milyin_Share');

15) Most Useful WordPress Code Snippets to Prevent Directory Browsing

You never want to give a stranger the map of your treasure; similarly, on WordPress, you do not want random people being your assets, various files, pressure server, and their locations.

Therefore, you need to Prevent Directory Browsing. This will ensure people can’t fiddle around your server folders and create a mess. Therefore, this Wonderful WordPress code snippet is a must-have for every WordPress site.

For Disabling Directory Browsing, go to your File Manager, public_html open .htaccess file, and in that file, add the below code.

# Disable directory browsing
Options All -Indexes

16) Restrict Access to wp-admin and wp-includes

Your WP-Admin and WP-Includes are important directories that control what WordPress does. The WP-Admin and WP-Includes folders are the most vulnerable due to the same.

Therefore, protecting this is essential. It includes some critical files, and the absence/editing of a single file is enough to cause the whole site to go down. 

This simple code in the .htaccess file can ensure no feeling into your Site.

Please note that this WordPress code snippet is to protect the file directories and not the actual wp-admin URL; it protects the code from being edited or stolen, and it does not impact the Access to wp-admin; wp-admin is safeguarded by your admin login name and password only. Other code snippets we discuss may help protect actual URLs, too.

# Block wp-includes folder and files

RewriteEngine On
RewriteBase /
RewriteRule ^wp-admin/includes/ - [F,L]
RewriteRule !^wp-includes/ - [S=3]
RewriteRule ^wp-includes/[^/]+\.php$ - [F,L]
RewriteRule ^wp-includes/js/tinymce/langs/.+\.php - [F,L]
RewriteRule ^wp-includes/theme-compat/ - [F,L]

17) Useful WordPress Code Snippet to Change WordPress Database Prefix

As most of you know, WordPress runs on SQL; WordPress has many SQL tables with essential data and the capability to hack your Site. 

The problem with WordPress has been that the default database prefix has been “wp_,” meaning that even without the hacker trying anything, he knows that your posts are stored in SQL Table wp_posts, and your users are in wp_users so he has already reached the door of your Tables.

Therefore, we would need to add obstacles. The best way to do it is to change the database prefix. Changing the database prefix to something that can’t be guessed ensures that they don’t know which Table they need; for example, if your WordPress prefix is  “wp_prefix_8503_,” then a hacker would probably hunt “wp_users” while in reality, that Table is called “wp_prefix_8503_users” making things challenging for it.

So, how do you do it?

Go to your File Manager, then in the public_html folder, open wp-config.php, and find the line having:

$table_prefix = 'wp_';

Now modify it to a random un-guessable string like:

$table_prefix = 'wp_difficult_to_guess_236_';

Now, you are good to go if you have a new site, but if your site is already live, you need to add the names of the actual tables als into your Hosting, go to your PhpMyAdmin or SQL runner, whatever your Hosting calls it.

Head onto the SQL Section and run the command:

RENAME table `wp_commentmeta` TO `wp_a123456_commentmeta`;
RENAME table `wp_comments` TO `wp_a123456_comments`;
RENAME table `wp_links` TO `wp_a123456_links`;
RENAME table `wp_options` TO `wp_a123456_options`;
RENAME table `wp_postmeta` TO `wp_a123456_postmeta`;
RENAME table `wp_posts` TO `wp_a123456_posts`;
RENAME table `wp_terms` TO `wp_a123456_terms`;
RENAME table `wp_termmeta` TO `wp_a123456_termmeta`;
RENAME table `wp_term_relationships` TO `wp_a123456_term_relationships`;
RENAME table `wp_term_taxonomy` TO `wp_a123456_term_taxonomy`;
RENAME table `wp_usermeta` TO `wp_a123456_usermeta`;
RENAME table `wp_users` TO `wp_a123456_users`;

Look into your actual Table,  find other SQL tables, and run a similar command there. Also, note that this code above was written with a random prefix; you need to edit this code to fit you.

Warning: This also is an advanced WordPress code; it can break down your Site quickly. Have someone with some SQL experience because you have to rename the instances inside the options and user tables where the prefix is the old WP_. However, I suggest you try your best to do it because this is one of the essential WordPress code snippets for Security.

23 Most Useful WordPress Code Snippets For Seo, Performance And Security Change Table Prefix

18) Useful WordPress Code Snippets to Hide htaccess and WP-Config

Your htaccess file handles Server Configuration Redirects and many other things. If you have noticed above, most of the code we discussed for Security was in the htaccess and WP-Config files, so what do we do to hide the files that manage the whole of Security?

So, the secure it? The htaccess can be edited to add a code to safeguard itself and WP-Config.

So let’s add the content to htaccess:

# Deny access to wp-config.php file

order allow,deny
deny from all


# Deny access to all .htaccess files

order allow,deny
deny from all
satisfy all

19) Disable Theme and Plugin editing in Admin

WordPress has its own editor Code editor. Anyone who gets into your wp-admin can edit your plugins, themes, and everything. You do not want to keep all your eggs in the same basket. Here’s the thing: You do not wish to have a Single login ID/password that can access everything from admin to files to database, etc.

So, we should not have a file manager in WordPress Admin; I agree that it makes editing files accessible, but it also makes things easier for a hacker. So, let’s be different and not have the File Manager there.

It has a lot of direct benefits, but it is especially suitable to have if your Site gets hacked; I shall tell you how it is also helpful in Code Snippet 23.

// Disallow file edit
define( 'DISALLOW_FILE_EDIT', true );

20) Smart Code Snippet to Change WordPress Security Keys

WordPress has Security Keys; these Keys are encryption things. They are used to encrypt your Cookies, user data, and passwords, along with many other things; the idea is that even if someone gets to see it, you still have some encryption on it, so you have to do a lot of decoding before you know what is there.

With time, it can be that the Secret Security Keys get decoded or are leaked. Therefore, we should frequently update these keys. They live in a wp-config.php file, so you must be. As a best practice, it would be best if you edited this code snippet in your wp-config file.

Some lines in wp-config must define AUTH_KEY, SECURE_AUTH_KEY, etc. So it would be best if you went to WordPress Salt Generator.

And edit the code that you get from there into your WP-Config file. Something like this

define('AUTH_KEY',         '~&nZt_:VTF,5:Uw,WW-)r:cBxT=Y*wxTjsD%K-+n|ZcaQCv]FpF EIK^K M:T^vB');
define('SECURE_AUTH_KEY',  ')*px;+wP:KEvFU;/42DwA$<;TdFf?Uj_o9vibUd/Af0Ff(/gh>M(U=~s#9TVT`Ce');
define('LOGGED_IN_KEY',    'iMxWB7E;|2pcf|WfkBCKT@8]OuN~R|GBc!x/Q1 i8rqfG!2FCWy t;P+Puo4x*+@');
define('NONCE_KEY',        '5hW^QC+DNFcYWZxMXVP@$Ael9 l-A%,3zl.|.]R!^$cZhMUH-{0Ppmm-i~hV)RB~');
define('AUTH_SALT',        '$Mr>-5hL!Pa(;PP,~QO,nlp@$zZXc;LqSzkNq`l^;p9{U>21+

21) WordPress Code Snippet to Ban Particular IP Addresses with Bad Record

There can be some IP addressing trying to guess your password or reset your password in WP-Admin; you need to be using Some IP tracking service to know which IP Address is doing that, but once you know, you can permanently ban those IP addresses. Do note that a Security Plugin like WordFence is a Far better idea.

You can ban the specific IP addresses by typing them in htaccess

Deny from 123.123.123.123

Here, I assumed the IP address to be 123.123.123.123, but if you want to add multiple IP addresses, you can add them in the same line, separated by spaces.

Deny from 123.123.123.123 234.234.546.645

22) Do not allow bots to open or use your Site

While most of us want bots like Google Bots to visit and index/understand your Site, it is sure that we don’t want random bots to come and fill in our Contact Forms and do spam and various other things, so the best way to restrict any such item is using the code below; this is a PHP code.

If you are using some plugin, then p, they probably are of it right out of the box, but the code below your own Plugin to ensure that regardless of what they do and what they are, they can’t access your content.

$user_agents = array( 'GTmetrix', 'Googlebot', 'Bingbot', 'BingPreview', 'msnbot', 'slurp', 'Ask Jeeves/Teoma', 'Baidu', 'DuckDuckBot', 'AOLBuild' ); 
		$user_agent = $_SERVER['HTTP_USER_AGENT']; 
		foreach ( $user_agents as $agent ){ 
			if ( strpos( $user_agent, $agent) ){ 
				$Bot= true;
			}
		}
		if(strlen($_SERVER['REQUEST_URI']) > 255 || stripos($_SERVER['REQUEST_URI'], "eval(") || stripos($_SERVER['REQUEST_URI'], "CONCAT") ||  stripos($_SERVER['REQUEST_URI'], "UNION+SELECT") || stripos($_SERVER['REQUEST_URI'], "base64")){
		 	$Request = 'bad';
		}
		if($Bot=== false && $Request != 'bad' && (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/BOT|google|yahoo|bing|spider|checker|discover|slurp|bot|crawl^$/i', $_SERVER['HTTP_USER_AGENT']))){ 
 // Your Code goes here		
}

23) Get Backdoor Entry into Your Site if you can’t access WP-Admin

Now we are at the end of this beautiful post; I hope I can help you achieve everything you need for your Site with the help of these 23 Most Useful WordPress Snippets for Performance, SEO, and Security.

But there’s one more thing: Imagine somehow your sSite gets hacked, and you can’t access wp-admin, so what do you do?

Remember I taught you how to disallow file editing in WordPress Admin in Point 19? Here’s how it would be helpful. If someone hacks your Site, removes you from admin, and you cannot access admin, then getting back is not very tough.

Below is a code that can be used to create a new WordPress Admin user programmatically; you need to put it in your Plugin. Remember, in the code, I have shown a user generation with a random username, email, and password. Use your email and username instead.

function wpb_admin_account(){
$user = 'Username';
$pass = 'Password';
$email = 'email@domain.com';
if ( !username_exists( $user )  && !email_exists( $email ) ) {
$user_id = wp_create_user( $user, $pass, $email );
$user = new WP_User( $user_id );
$user->set_role( 'administrator' );
} }
add_action('init','wpb_admin_account')

Conclusion

That’s been it. Thanks for reading this Creation about 23 great WordPress Snippets for Performance, SEO, and Security. As always, in case you need help, I am always a comment away.

Aditya AgarwalLast Seen: Nov 25, 2023 @ 6:35am 6NovUTC

Aditya Agarwal

@AkarshitMahajan6300





Published: | Last Updated: | Views: 1094

Hasthags:

You may also like

Leave a Reply