Introduction
The functionality of WordPress can be extended through the use of plugins. It can also be extended by editing the functions.php file of the theme that the WordPress site is using. But what if we just need to add a an enhancement that only does a single thing? A possible answer is to create a site-specific plugin. However, a problem arises. What if we need to add another small enhancement and another one after that? We would have a handful of plugins which are unrelated to one another. This can be a nightmare to manage. One way to deal with this is to cram all the code in a single plugin file or the functions.php. This only pushes the problem one step back however, It still gives rise to a management issue since the file will grow and grow the more you place code on it. Worse, a single bug in these files can stop your site from functioning. To remedy this, we can use the Code Snippets plugin. The plugin allows us to add small chunks of code for enhancements without the need to write a custom plugin or edit the functions.php. In adddition, we can even choose to activate or deactivate a plugin, just like we can with plugins.
In this article, we will be learning how to add code snippets to a WordPress site. In addition, we will be looking at the most useful code snippets.
Adding and Using Code Snippets
Installing the Code Snippets Plugin
We first need to install the “Code Snippets” plugin. To do that, we go the “Add Plugins” page from the admin dashboard, search for ‘Code Snippets’, then install and activate the plugin. Once that is done, you should see a new dashboard menu item with the text “Snippets” on it. Click on it and you will be redirected to the snippets page. This is where we can add, delete, and manage code snippets.
Using the Code Snippets Plugin
To add a code snippet, we click on the “Add New” link on the ‘Snippets” dashboard page. This will redirect us the the “Add New Snippet” page.
This is where we the snippets. Let’s see it in action. We will be adding snippet which disables the WordPress admin toolbar. This is what a site in a page looks like when it is viewed and you are logged in.
Now let’s add the snippet using the Code Snippet plugin and activate it.
This is what a page now looks like when you view it while it is still logged-in.
We can toggle to activate the snippet in the “Snippets” page. The plugin can also be edited, cloned, exported, or deleted there. So in case you need to do any of these, all you have to do is go to the plugin’s dashboard page.
The Most Useful Plugin Snippets
Now that we’ve seen how to add and use snippets, let’s take a look at some of them.
1. Disable WordPress Updates
This snippet allows us to disable WordPress. This is useful when we want to prevent the site from breaking due to plugin/theme compatibility issues caused by updates. All it takes is a single line:
define('WP_AUTO_UPDATE_CORE', false);
Code language: JavaScript (javascript)
(Credits: WPDean)
2. Disabling Automatic JPEG Compression
A lot of optimization plugins compress images on a WordPress site. This results in the quality of the images being reduced. We can prevent that however by using this snippet:
add_filter( 'jpeg_quality', 'smashing_jpeg_quality' );
function smashing_jpeg_quality() {
return 100;
}
Code language: JavaScript (javascript)
(Credits: WPDean)
3. Disable Admin Toolbar
The admin bar is very helpful for navigating WordPress sites. It is also handy as it allows us to create posts and users easily. However, there may be valid reasons to disable it. To disable the admin toolbar use this snippet:
add_filter( 'show_admin_bar', '__return_false' );
Code language: JavaScript (javascript)
(Credits: smartwp )
4. Disable Deleted Content Trash
By default, WordPress keeps the deleted content from your site in a specified period of time. This can be disabled though so that the deleted content does not take up space in your WordPress site’s database. We can use this snippet to disable that:
define('EMPTY_TRASH_DAYS, 0'); //Zero days
Code language: JavaScript (javascript)
(Credits: WPDean)
5. Minimum Post Content Length
it’s never good to have any spam content on your site. One way this can be done is to require posts to have a minimum length before they can be posted. Here is a snippet that can do that:
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;
}
Code language: PHP (php)
(Credits: WPDean)
6. Set website in maintenance mode
Site’s have to be maintained from time to time so it would be good to inform your users and visitors if maintenance is going on. You can do this by using a plugin, but an even better solution is available. We can use a simple snippet:
unction maintenace_mode() {
if (!current_user_can('edit_themes') || !is_user_logged_in()) {
wp_die('Maintenance.');
}
}
add_action('get_header', 'maintenace_mode');
Code language: JavaScript (javascript)
(Credits: borishoekmeije)
7. Remove links from the Dashboard
The admin dashboard has a lot of links but most users don’t use all of them. They can clutter the dashboard, making it hard to navigate. We can, however, hide the menu link. All we need to do is edit then use this snippet.
// Remove links item from WP-admin
add_action( 'admin_menu', 'remove_links_menu' );
function remove_links_menu() {
remove_menu_page('menuslughere.php');
}
Code language: JavaScript (javascript)
(Credits: borishoekmeije)
8. Disable default user roles
We may want to remove all user roles that are unused. This is how to do that with a snippet:
// Remove default user roles (from wpsnipp.com)
function wps_remove_role() {
// remove_role( 'editor' );
remove_role( 'author' );
remove_role( 'contributor' );
remove_role( 'subscriber' );
}
add_action( 'init', 'wps_remove_role' );
Code language: JavaScript (javascript)
(Credits: borishoekmeije)
9. Add user roles
There are also times where we may want to add roles for a user type. We can do that as well with a few lines of code using this snippet:
// Add user role & capabilities
function wps_add_role() {
add_role( 'manager', 'Manager',
array(
'read',
'edit_posts',
'delete_posts',
)
);
}
add_action( 'init', 'wps_add_role' );
Code language: PHP (php)
(Credits: borishoekmeije)
10. Redirect users to previous page after logging in.
It’d be good to redirect users to the page they were viewing after logging in. This saves a lot of time and is just a good feature. We can do just that using this snippet:
// Redirect users to previous page upon login
if ( (isset($_GET['action']) && $_GET['action'] != 'logout') || (isset($_POST['login_location']) && !empty($_POST['login_location'])) ) {
add_filter('login_redirect', 'my_login_redirect', 10, 3);
function my_login_redirect() {
$location = $_SERVER['HTTP_REFERER'];
wp_safe_redirect($location);
exit();
}
}
Code language: PHP (php)
(Credits: borishoekmeije)
11. Disable Search in WordPress
You may want your site’s search function to be disabled for whatever reason. Here’s a snippet to do just that:
function fb_filter_query($query, $error = true)
{
if (is_search())
{
$query->is_search = false;
$query->query_vars[s] = false;
$query->query[s] = false;
// to error
if ($error == true) $query->is_404 = true;
}
}
add_action('parse_query', 'fb_filter_query');
add_filter('get_search_form', create_function('$a', "return null;"));
Code language: PHP (php)
(Credits: thethemeisle)
12. Limiting WordPress Post Revision
Whenever you revise a post on WordPress, a copy of the content, prior to being edited, is kept in the database. Many revisions would case the database to bloat. We can limit the revisions or we can even choose to disable revisions altogether. We can do that with this snippet:
if (!defined('WP_POST_REVISIONS')) define('WP_POST_REVISIONS', 5);
if (!defined('WP_POST_REVISIONS')) define('WP_POST_REVISIONS', false);
Code language: JavaScript (javascript)
(Credits: WPKube)
13. Using the Current Year in Your Posts
Shortcodes allow us to embedded content that has already been created. One good shortcode is to display the current year on our post and pages. Here is a snippet for that:
function year_shortcode()
{
$year = date('Y');
return $year;
}
add_shortcode('year', 'year_shortcode');
Code language: PHP (php)
(Credits: WPKube)
14. Remove the Comment URL Field
Spammers who visit your site may decide to post links on URL field. Aside from adding clutter to the comments, they may pose a security risk for your users. There is a way to prevent this though. We can use this snippet that disables the URL field.
function remove_comment_fields($fields)
{
unset($fields['url']);
return $fields;
}
add_filter('comment_form_default_fields', 'remove_comment_fields');
Code language: PHP (php)
(Credits: WPKube)
15. Show X Results on the Search Results Page
The last snippet we’ll look at allows us to limit the number of posts that we can see after a search. This is useful since we do not want to sacrifice the readability of the search results for ease of access. This is the snippet that limits the posts retrieved:
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');
Code language: JavaScript (javascript)
(Credits: WPKube)
Conclusion
We’ve seen how to use the Code Snippets plugin and also have seen some useful code snippets that we can use. These snippets are only a few of a hundred, if not a thousand. Now you may be wondering, whether you should use a plugin or snippet. Here’s our answer – use plugins for feature enhancements that have an extensive scope and use a snippet when the scope is not extensive.
We’ve come to the end of the article. Thank You for reading.