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

23 Most Useful WordPress Code Snippets for Performance, SEO and Security

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 are Extremely Useful, and can help reduce plugin burden on your WordPress site.

WordPress is a really powerful platform, and the best part of WordPress is the ability to customize anything and everything based on your need. I have brought for you 23 Most Useful WordPress Code Snippets to Improve SEO, Performance and Security. While plugins are really good, and plugins can do a lot of work, but Plugins can slow you down, and many times plugins cause conflicts also, ask any WordPress Plugin Author about an error in there plugin, the first thing they tell is to check whether any other plugin is not troubling. Moreover, sometimes you need just a small feature and still you have to install a big fat plugin for it. It’s like using a Sword for the work which can be done by just a Knife… So here I bring you 23 Great WordPress Code Snippets to Improve SEO, Performance, Security. You do not need to Worry, even if you do not know coding, I will first help you create your own plugin in your WordPress Installation, so don’t worry.

0. Create Your Plugin

Your custom plugin is where you put most of the code, so it’s better to create a plugin as a Starting, though not all the code is in Plugin, some code (specially Security ones), so let’s create a Plugin, but how to do that?

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

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

So to manage files, you need some place to edit/access them. If you are using some Good Hosting provider, like Bluehost or Siteground it wont be a trouble. They have there File Managers, you just need to login to the Hosting provider, and go to your site, and find out the File Manager.

A file manager is really important, we do not recommend using WordPress plugin to edit files, as all of them are fragile. For using our 23 Great Code Snippets for WordPress and bettering Performance, SEO and Security, you need to have a Hosting based File Manager, or a 3rd Party FTP. FTP stands for File Transfer Protocol

In case your provider does not give direct File Editor, they give you the FTP details directly, others you can generate your credentials. FTP runs on PORT 21, and SFTP runs on port 22. Port 22 is relatively secure, therefore is possible use that. So now you need some application through which you can login to FTP.

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

So once you are in, you shall have a File Manager of 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 where you should reach, some file managers omit the initial locations, but after public_html its mostly same.

{domain_name}/public_html/

Now we are ready to get onto developing. To save you time, and be useful 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 representing One Plugin. So as it might be obvious let’s create a plugin for you.

So decide the name for your cool 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. Now if you refresh the plugins page, in wp-admin, then you wont see this plugin. Because we have another step.

Again in your file manager, now open the plugin folder which we just created. it should be empty. Create a file in it, you can name it almost anything, but for the sake of best practice, it’s good to name it same as your plugin name. Now 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, of actual code. So, be a little careful. Though, in a few paragraphs 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 to keep 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 created your first ever plugin.

First of all open wp-config.php, just in case 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 so as 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 for Performance

For every #WordPress site, the usage of too many plugins, can be troublesome, it can generate conflicts and it can be slow too. As a result always use custom #CodeSnippet, as they do not execute extra code which has no use for you. Now you are into your File Manager, and we shall start with variety of things to increase speed.

I have compiled the list of these 23 Code Snippets, all of them are #Secure, #Fast and Simple at the same time. I have tried to add comments everywhere to explain you 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.

In case you want to see the Plugin/3rd Party service based Implementation for Improving WordPress Performance refer to this article: How I Optimized my WordPress Website.

abcd

1.) Leverage Browser Caching

Now this one is really good, all Modern Browsers support caching. Caching can be used to serve the resources frequently loaded on your site directly from browser rather than downloading from server. 

Important thing to note is, that for it, 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 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 every one can do. Again if you have any problem what so ever, I am always available in Comment Section below.

Also many a times, updating this file can cause some weird things to happen on site. As a result whenever you update 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 which is a JS file to bridge old jQuery files with new. It is useful for people who have old jQuery code which is incompatible with newer jQuery.

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

So, vast majority of people with sites newer than 2012 (WordPress 3.6), do not need jQuery Migrate library. Therefore its better to remove jQuery Migrate from WordPress on frontend.

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

//Your Future Code Goes Here

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

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

 

Let me just explain the above function to you. The above function goes through this function runs whenever the wp_enque_scripts action happens. the wp_enqueue_scipts is responsible for attaching all javascript files on #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, then we deregister jQuery Migrate, so that it doesn’t gets attached to webpage.

Personally I always do it in any of the sites I design, it’s such a useless thing for all modern sites.

3.) WordPress Code Snippet to Prevent Hotlinking | Be Selfish

Imagine, that you brought a cake for your son’s birthday, and you hide it at your friends home to give your kid a surprise, but when you open it you find your friend has ate half of it, you would feel bad right? You spent money, but he got reward. That’s the same in internet.

Your server has finite resources, and some clever people, can try to load images that exist on your server, for there site. Meaning that some other site is loading images from your site, meaning that your server resources are consumed for there benefit. Bad right?

That’s called Hotlinking, and for most of the sites, it should be stopped. So that only your site can load images from your servers. And your resources are exclusive. Moreover it is good for Security also. As you may want images 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 them. But usually they are almost never used in frontend. Most of the plugins now a days either use Favicons or there own custom Icon Font. As a result we should not waste time optimizing for something which would have close to 0 impact on frontend.

So below is the code for same. You need to paste this also in your custom WordPress plugin. 

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 size of your webpage, meaning less time to load. It works like magic, though for this magic you would need to wander through your file system.

Based on your Hosting Provider, the php.ini file.

This file has the configuration for how #PHP and it’s 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

 Turn it on, to turn on gZip compression.

gZip is one of the most Important 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 be aware of the fact that WordPress uses an Autosave functionality, and saves your content while you are writing it in backend.

Unfortunately this content is saves as a seperate posts, in my case, I have had some posts with over 350 revisions, this meant that for a single post, WordPress had done 350 autosaves. And most of them were useless to me. And they slow down site. While Autosave can be useful, I suggest to limit it to 20.  This is a Useful WordPress #Code Snippet for optimization, but if you have really less posts or if you forget to save your posts almost every time, then you should forget using this.

Opening the wp-config.php file (domain.com/public_html/wp-config.php) you shall scroll down to 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 that, in the line that you added, there is a number “20” in it. It means that WordPress would maintain the latest 20 Revisions, and delete everything prior to 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 important. Like you don’t like trash in your home, you should not like Trash in WordPress also. WordPress can keep trash for months, without anything changing. Therefore as a Best Practice you should ensure that your site doesn’t get choked due to the posts that you deleted but still are sitting in your trash. This is one of the 23 most useful WordPress Code Snippets for Speed, SEO and Security but if you are a careless fellow then you should keep it 15 days.

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

Add the below code there 

define('EMPTY_TRASH_DAYS', 7);

8.) Disable Heartbeat API

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

You can do it easily with adding the below lines of code into the plugin that we 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');
}

Most Useful WordPress Code Snippets for SEO

If you feel we have done too much of optimization, then sure, I shall let you go to SEO. SEO is as important as Speed and Security for sites. A site with SEO in mind is loved by all. Though sometimes SEO can be time consuming, like in case of Image ALT tags, and sometimes it can slow down site, like in case of Sitemap plugins, therefore I shall give you some secret recipes for this doing it all.

I have worked really 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 important for every site. Sitemaps make navigation easy, and when submitted to google, they make indexing and ranking of your site on Search Engines simple. There are many plugins in the WordPress directory, which can make sitemaps with ease. The problem with them is that they slow down your site. This is because some of them 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.

Rather I found some code on Internet, and with some improvisation of my own, I shall give you a code to make update sitemap whenever 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 in your Hello-Plugin folder create a file called “sitemap.php” and save it.

Before proceding it’s better to check that your site is fine. Just open your site and ensure things are fine, and then do the next step.

So the next step is to build the actual sitemap.

You just need to copy paste the below code in your sitemap.php, nothing else, it is compatible with woo-commerce too, so your woo-commerce products also get added into it by default. It shall make a sitemap of all posts order by 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 open any post and click save button. As it is generated every time a post is saved/updated/published. and then 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. And Optimizing images to rank easily on Google is equally necessary. We all know that there are some WordPress specific Image Text fields such as Captions, and there are some SEO specific fields such as Alt Text. Now everyone should utilize them all in there site as it can be really helpful.

But in most cases, we are too lazy to type it in. Therefore, it’s better to rather have little automation. I built a code for you guys which 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” and the code will automatically set the Alt Text, Caption, Description, Title as “Person Sitting with a Laptop”

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

This is literally not only just Useful but a really 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 important thing in the world of SEO. Meta Description is what decides the conversion rate. Meta Description is what improved your conversion rate.

It is said that first 100 words of your post are the most important thing after the Title/Content itself. I believe that if these 100 words are good enough, then it is better to extract the first few words out of them and use it as Meta Description.

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

Meta Descriptions is immensely important and WordPress does not have direct way to add Meta Descriptions, which sometimes makes me feel bad.

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

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 Content is important. At start of post having Table of Content helps make things clearer. It sets the town and the agenda of what all will be covered in the post. Besides that Table of Content also means, that each heading would have it’s own ID, and Google would recommend going directly to a Heading in search snippets.

It would look something like this.

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

 
/**
 * cd-table-of-contents.php
 */

class TableOfContents {

    /**
     * Counts the occurence of header elements in WordPress content
     * 
     * @param type $content
     * @return null|boolean|array
     */
    static function hasToc($tiers, $content) {

        $pattern = '/<h[2-' . $tiers . ']*[^>]*>(.*?)<\/h([2-' . $tiers . '])>/';
        $return = array();
        if (empty($content))
            return null;

        if (!preg_match_all($pattern, $content, $return)) {
            return false;
        }
        return $return;
    }

    /**
     * Generates a table of content only when singular pages are being viewed
     * 
     * @param type $tiers
     * @param type $text
     */
    static function generateTableOfContents($tiers, $content, $draw = TRUE, $return = array()) {

        if (!is_singular())
            return $content;

        // numbers on or off?
        $num_on = true;

        $content = $toc . $content;
        $searches = array();
        $replaces = array();
        $return = (is_array($return) && !empty($return) ) ? $return : TableOfContents::hasToc($tiers, $content);

        if ($draw && !empty($return)):
            if($num_on){
                $toc = '
‘; }else{ $toc = ‘

‘; } $toc .= ”

Table of Contents

“; $toc .= ”

    $htag) { $count++; $attributes = array(); $href = $count; $newId = ‘id=”‘ . $href . ‘”‘; $newhtag = ‘>’; $htagr = str_replace(‘>’ . $titles[$i], “\t” . $newhtag . $titles[$i], $htag); $searches[] = $htag; $replaces[] = $htagr; if ((int)$levels[$i] === (int)$_level): if($num_on){ $chapters[$_level-1] = ((int)$chapters[$_level-1]+1); $chapter = implode(‘.’, array_slice($chapters, 1, ($levels[$i]-1) ) ); $toc .= ‘

  • ‘ . strval($chapter) . ‘ ‘ . $titles[$i] . ‘
  • ‘; }else{ $toc .= ‘

  • ‘ . $titles[$i] . ‘
  • ‘; } endif; if ($levels[$i] > $_level) { $_steps = ((int) $levels[$i] – (int) $_level); for ($j = 0; $j < $_steps; $j++): $toc .= ‘

      ‘; $chapters[$levels[$i]-1+$j] = (int)$chapters[$levels[$i]-1+$j]+1; $_level++; endfor; $chapter = implode(‘.’, array_slice($chapters, 1, ($levels[$i]-1) ) ); if($num_on){ $toc .= ‘

    1. ‘ . strval($chapter) . ‘ ‘ . $titles[$i] . ‘
    2. ‘; }else{ $toc .= ‘

    3. ‘ . $titles[$i] . ‘
    4. ‘; } } if ($levels[$i] < $_level) { $_steps = ((int) $_level – (int) $levels[$i]); $chapters[$levels[$i]-1] = (int)$chapters[$levels[$i]-1]+1; $_olevel = $_level; for ($j = 0; $j < $_steps; $j++): $chapters[$levels[$i]+$j] = 0; $toc .= ‘

    ‘; $_level–; endfor; $chapters[$_olevel-1] = 0; $chapter = implode(‘.’, array_slice($chapters, 1, ($levels[$i]-1) ) ); if($num_on){ $toc .= ‘

  • ‘ . strval($chapter) . ‘ ‘ . $titles[$i] . ‘
  • ‘; }else{ $toc .= ‘

  • ‘ . $titles[$i] . ‘
  • ‘; } } } $toc .= ‘

‘; $toc .= ‘

 

‘; $content = str_replace($searches, $replaces, $content); $content = $toc . $content; endif; return $content; } /** * Appends the table of content to the $content * AKA. Executes our filter * * @param type $content * @return type */ static function writeToc($content) { $content = TableOfContents::generateTableOfContents(4, $content, TRUE); return $content; } } add_filter(‘the_content’, array(‘TableOfContents’, ‘writeTOC’));

Full Credits 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 Hansle and Gretel, how they left Breadcrumbs to give hint of direction. Same is with Web, we need breadcrumbs to tell Hierarchy, Breadcrumbs tell where 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, which is like “yoursite.com  | Blog | Blog-Post”

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

Warning: This is a powerful WordPress 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.
$Breads = explode("/",$_SERVER["REQUEST_URI"]);
echo '
';

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 are lazy enough to not have 10sec 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 which does the same.

It has 4 buttons, Facebook, Twitter, Google Plus and Linkedin, clicking them takes you to there respective site, with the link of your post with it, so a person can click the button, and directly share the link of your post, on any of these platforms.

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

This WordPress Code Snippet runs on the WordPress Shortcodes. It adds a Shortcode into 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');

Most Useful WordPress Code Snippets for Security

15. Most Useful WordPress Code Snippets to Prevent Directory Browsing

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

Therefore, you need to Prevent Directory Browsing. This will ensure people cant fiddle around your server folders and create a mess. Therefore this Wonderful WordPress code snippet is a must have for each and 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, as they actually control what WordPress does. And the WP-Admin and WP-Includes folder are the most vulnerable due to the same.

Therefore protecting this is really important, it includes some really important file, absence/editing of a single file is enough to cause whole site to go down. 

This simple code in .htaccess file can ensure no fideling into your site.

do note, 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, it does not impact the access to wp-admin, wp-admin is safeguarded by your admin login name and password only. Though other code snippets which we discuss may help with protecting 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 already know, WordPress runs on SQL, WordPress has many SQL tables, with important data, and the capability to hack your site. 

The problem of WordPress has been that, the default database prefix has been “wp_”, meaning that even without 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 cant be guesses ensures, that they don’t know which table do 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 tough for it.

So how to do it?

Go to your File Manager, then in 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, then you need to change the name of actual tables also. Go 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`;

Have a look into your actual Table and find any other SQL tables, and run the similar command there also, do 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 has the capacity to break down your site easily, therefore have someone who has little bit SQL experience, because you have to rename the instances inside the options and user tables also where the prefix is the old wp_, though i suggest, try your best to do it, because this is one of the most important 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, and if you have noticed above then most of the code that we discussed for security was in htaccess and WP-Config file, so what do we do hide the files that manage the whole of security.

So how do you secure it. Well the htaccess can be edited to add a code to safeguard itself as well as 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 it’s own editor Code editor. Now anyone if gets into your wp-admin, he can edit your plugins your themes everything. You do not want to keep all your eggs in the same basket. Here’s the thing, you do not want to have a Single login ID/password that can give access to everything from admin to files to database etc.

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

It has lot of direct benefits, but is specially good to have if your site gets hacked, I shall tell how it is useful in Code Snippet 23 also.

// 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, idea is that even if someone gets to see it you still have some encryption on it, so you have to actually do lot of decoding before you actually 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 wp-config.php file, so you need to again be in that file. You should edit this code snippet in your wp-config file every 30 days or so, as a best practice.

there must be some lines in wp-config which define, AUTH_KEY, SECURE_AUTH_KEY etc. So you need to go 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|[email protected]]OuN~R|GBc!x/Q1 i8rqfG!2FCWy t;P+Puo4x*[email protected]');
define('NONCE_KEY',        '5hW^[email protected]$Ael9 l-A%,3zl.|.]R!^$cZhMUH-{0Ppmm-i~hV)RB~');
define('AUTH_SALT',        '$Mr>-5hL!Pa(;PP,~QO,[email protected]$zZXc;LqSzkNq`l^;p9{U>21+<iD`?*|2h?hl7pP');
define('SECURE_AUTH_SALT', '{ED(GhQ.x*iW4U-V-JatW~or|^L$;;|aV9iM=yc^/T-fYB{y&e]R!W)');
define('LOGGED_IN_SALT',   'R].yo;rW7,G } C;5r3w[tnLtax[f`9]Q*6!+jjohAo`%<|+o=iWLf.1sSX,aC]v');
define('NONCE_SALT',       '*}?6!]%DS)/cCAdP*x:~%8t0Wx_Ug_lF=qJ$%A0lf8Hob{8{rV.=fl?dY$Rr*8dC');

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

There can be some IP addressing trying to guess your password, or may be trying to 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 for this a Security Plugin like WordFence is a Far better idea.

You can ban the specfic 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 same line, seprated with 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 thing, is using the code below, this is a PHP code,

IF you are using some plugin then probably they take care of it right out of box, but the below code is for your own plugin, to ensure that regardless of what they do, and regardless of how smart 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 wonderful post, I hope I could 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 site gets hacked, and you aren’t able to access wp-admin, so what do you do?

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

Below is a code, that can be used to create a new WordPress Admin user programmatic, you need to put in your plugin, remember, that in the code, I have shown a user generation with random username, email and password. Use your own email and username instead.

function wpb_admin_account(){
$user = 'Username';
$pass = 'Password';
$email = '[email protected]';
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')

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



Published:
Last Updated:
Views: 774
Leave a Reply