Understanding WordPress and its capabilities are always a challenge for the beginners and the experts. WordPress, being a beginner friendly CMS, can provide the impression that the experts or post-beginner skill people cannot utilize its code base to customize it. But that’s not the truth.

WordPress is open source and that’s where it shines the most. You can add snippets to the core functions file or the themes and extract more functionality and usability than the non-customized WordPress has to offer.

WordPress Code Snippets

But do you need to customize WordPress using snippets when there is a plugin for anything you can think off? The answer is Yes. Plugins are great, but they make the core WordPress(already bulky) to more bulky, impacting loading time of the website.

Using snippets means adding minor changes without impacting loading time and other functions that WordPress has to offer.

Before, we start, it is a good idea to take few precautions. Let’s discuss them below.

  • If you are using code snippets in your “functions.php” and mess up anything. Before starting you, backup WordPress. Fixing bugs might take a lot of time, but it is always easy to revert back to the working state of the website using the backup.
  • Using a snippet plugin such as Code Snippets. By using the plugin, you can keep track of all the custom codes, and enable and disable them when needed.
  • The best way to work with modifications, either functions or the CSS modification, is to use a child theme. The child theme offers better management and also preserves the changes after any theme or WordPress updates.

Without much ado, let’s get started with the useful code snippets for WordPress.

Useful Code Snippets For WordPress


# Reducing Post Revisions

Writing on WordPress is fun and at the same time useful too. WordPress is intelligent enough to save your draft as revisions so that you can divert back to any of the revisions whenever needed.

The revisions or WordPress revision system is used to save information, in case you lost connection or your machine rebooted without warning.

Amazing, right? But, the revisions storage in the database is unlimited and can easily overburden the database, slowing down your website a tiny bit.

Imposing a limitation can solve the issue. By using the following code in the wp-config.php file, you can easily put a limit. Change the number to anything you want seems reasonable. For me, 5 is a good number.

define('WP_POST_REVISIONS', 3);

Some people might want to disable post revisions altogether. Use the following code to do it.

define('WP_POST_REVISIONS', false);

# Clearing W3 Total Cache Automatically

W3 Total Cache is one of the most used plugins for WordPress. It is commonly listed in must use plugins for WordPress and there is less chance that you are not using W3 Total Cache.

If you are reading W3 Total Cache and a dynamic site, you can easily automate the old cache and deliver content on the go.

Use the following code to acheive the desired result.

if (function_exists('w3tc_pgcache_flush')) {
w3tc_pgcache_flush();
}

The above code is used for purging the entire cache.
The below code is used to purge individual post/page cache.

if ( function_exists('w3tc_pgcache_flush_post') ) {
w3tc_pgcache_flush_post($post_id);
}

# WordPress Automatic Updates

WordPress updates are tricky. For many of us, updating means finding solutions to plugins that stop working after the update. Automatic updates may cause problems and that’s why it is always a good idea to disable automatic updates.

Critical updates, on the other hand, should be kept enabled.

To disable the automatic updates, just add the following line in the wp-config.php file.

define('WP_AUTO_UPDATE_CORE', false);

# WordPress Version Number

WordPress is the most used CMS in the world. And, this makes it the best target for hackers as well. To make sure that WordPress version is hidden from the public, add the following line of code in your functions.php file.

<?php
// Remove the version number of WP
// Warning - this info is also available in the readme.html file in your root directory - delete this file!

remove_action('wp_head', 'wp_generator');
?>

# Disabling Automatic JPEG Compression

Most of the WordPress blogs/website use image optimization plugins, such as WP Smush. It is a good idea to disable the built-in image optimizer. The built-in image optimizer reduces the quality of the image to 90 with no real-world visual difference.

add_filter( 'jpeg_quality', 'smashing_jpeg_quality' );

function smashing_jpeg_quality() {
return 100;
}

We also recommend to try some lazy load plugins for better optimization and fast load times.

# Improving Website Caching

Caching is very important for any website. To leverage caching, you need to use the correct commands in .htaccess files.

Use the following code in your .htaccess to enable browser caching and improve the website loading time for users across the world.

## EXPIRES CACHING ##
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month" ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 2 days"
## EXPIRES CACHING ##

Always remember to backup the .htaccess file before making any change.

# Making Search Results More Refined and Controlled

There are many scenarios when a certain page or post should not show up in the search results. To make sure that it happens, you need to make some code editing in your function.php file.

Private pages can also be hidden with this technique. Just make sure to backup everything before making the changes.

function filter_search($query) {
if ($query->is_search) {
$query->set('post_type', 'post');
}
return $query;
}

add_filter('pre_get_posts', 'filter_search');

And, we are done.

# Optimizing the Dashboard with Customized Message

Whenever you login in your WordPress dashboard, you are welcomed by the automated system, “Howdy, User Name“. At the start, it looks great. But, you might want to replace it with the user that is logged in your website.

Without replacing the name, it can seem that the admin is watching you or similar kinds of reaction. To make sure that the user is comfortable, you need to customize a little.

Adding the following code to the function.php file will do the necessary trick.

function replace_howdy($wp_admin_bar) {
$my_account = $wp_admin_bar->get_node('my-account');
$newtitle = str_replace('Howdy', 'Logged in as', $my_account -> title);
$wp_admin_bar -> add_node(array(
'id' => 'my-account',
'title' => $newtitle,
));
}

add_filter('admin_bar_menu', 'replace_howdy', 25);

# Modulating the number of Searches that are shown in the search page

No one wants to scroll long in a search page. That’s why you can limit the number of searches returned and hence improve overall user search experience.

function limit_posts_per_search_page() { 
if ( is_search() ) 
set_query_var('posts_per_archive_page', 20); 
} 

add_filter('pre_get_posts', 'limit_posts_per_search_page');

# Controlling URL spam with a simple Function

Spam is a never ending process, and there are chances that your website also takes a lot of tolls when it gets spam comments. The spam comments generally have long URL in their content. You can easily ban them using a simple snippet discussed below. The below snippet works for URL longer than 50 characters. You can change the number according to your preference.

<?php
function rkv_url_spamcheck ($approved, $commentdata ) {
return(strlen ( $commentdata['comment_author_url']> 50 )? 'spam' : $approved;
}

add_filter( 'pre_comment_approved', 'rkv_url_spamcheck', 99, 2);
?>

# Setting minimum Content length

We have already discussed on how spamming can be determinable for blogs/website. Now, we will make sure that spammers don’t run away with just small sentences or taunts.

By using the following snippet, you can easily add minimum comment length to the blog/website. The code needs to be added to the Functions.php file and would ask the user to add a more valuable comment rather than a two word reply.

add_filter('preprocess_comment', 'minimal_comment_length');
function minimal_comment_length($commentdata) {
$minimalCommentLength = 20; //change it according to your requirement

if ( strlen(trim($commentdata['comment_content'])) < $minimalCommentLength) {
wp_die('All comments must be at least' . $minimalCommentLength . 'characters long')

}
return $commentdata;
}

# Redirecting user registration to a specific page

User registration is a common practice among website. If a user registers, there are chances that he/she get redirected to the homepage of the website. The default behavior can easily be modified using the following snippet.

Backup the Functions.php file before making any changes to the original file.

function wps_registration_redirect(){
return home_url('/finished/');
}

add_filter('registration_redirect', 'wps_registration_redirect');

# Emptying WordPress Trash For the Greater Good

WordPress trash is generated whenever you delete a post, page or any media files. This is a fail-safe system that prevents losing important data due to human error.

The trash is emptied every 30 days and can easily bob down the website performance, especially database quering. The good news is that you can easily change the default 30 days trash time to a lower value.

All you need to do is add the following line of code in the wp-config.php file.

define('EMPTY_TRASH_DAYS', 10 ); // 10 days

Want to disable the trash without any backup? Add the following line to the wp-config.php.

define('EMPTY_TRASH_DAYS, 0'); //Zero days

Disabling the trash system is not recommended as it will give you no chance to retrieve deleted items.

What Else?

Apart from using these useful WordPress code snippets, it is recommended to use a fast WordPress theme which can control other aspects of site and helps your site loads faster for your visitors.

Wrapping it Up

Today, we went through the list of useful snippets. The snippets listed here are in no way complete, any comments or new snippets links are welcome through the comment section below. Also, don’t forget to share the articles with your peers!

Now Read: 12 Unconventional Ways to Use WordPress

15 Useful WordPress Code Snippets For Enhanced Site Performance
4.3 (85.45%) 11 votes