5 Reasons (And Ways) to Use Code Snippets in WordPress Development

As you likely already know, you can expand the functionality of your WordPress site with custom code snippets. Unfortunately, adding them incorrectly to your functions.php file could break your website.

Fortunately, the Code Snippets plugin makes adding custom code to your website easy. It also helps you keep everything organized in a way that is difficult to achieve when simply pasting snippets into your functions.php file.

In this article, we’re going to look at what the Code Snippets plugin is and what it does. We’ll then explore five ways you can use it on your website. Let’s jump in!

Introducing the Code Snippets plugin

To customize a website, you sometimes need to add code to your site’s theme. While you can sometimes accomplish this with help from plugins, they’re not always necessary. For simple functionality changes, adding code snippets may be the better option.

Code snippets are small pieces of reusable code. They contain the necessary commands to expand or restrict website functionality. Developers can add snippets to a WordPress theme’s functions.php file manually. However, this can break the website if it’s not done correctly.

Especially if you’re new to WordPress development, you may want to leave your functions.php file alone. If that’s the case, the Code Snippets plugin can help:

Cover for the Code Snippet plugin.

It has a graphical interface, similar to the WordPress Plugins screen. Here you are can add, remove, activate, and deactivate code snippets on your site:

The graphical Code Snippet user interface.

Using Code Snippets, you never have to enter the functions.php file. You can also manage your custom code more effectively. Each snippet includes a description and tag for organization and tracking.

This is useful for monitoring how you’ve customized a client’s site. It also makes it easier to ‘turn off’ snippets if a client asks you to remove a certain custom feature. Instead of trying to remember where you added it, you can simply deactivate or delete it via the Code Snippets plugin.

5 reasons (and ways) to use Code Snippets in WordPress development

The Code Snippets plugin can be a very powerful tool in WordPress development. It makes extending the functionality of your client sites much faster and safer, while also helping you maintain your customizations over time. Here are five ways that you can use it to enhance your projects.

1. Remove default widgets

Every WordPress installation comes with default widgets. They can be useful for adding permanent content to sidebars and footers, but there are probably many of them you’ll never touch:

Widget page with multiple unused default widgets.

These widgets may not impact website performance, but they create clutter on the back end of your sites. This makes it harder to find the widgets you need, and could result in confused clients making unnecessary changes. In most cases, it can be helpful to simply remove them.

To remove default widgets, you’ll need this code snippet:

// unregister all widgets
function unregister_default_widgets() {
unregister_widget('WP_Widget_Pages');
unregister_widget('WP_Widget_Calendar');
unregister_widget('WP_Widget_Archives');
unregister_widget('WP_Widget_Links');
unregister_widget('WP_Widget_Meta');
unregister_widget('WP_Widget_Search');
unregister_widget('WP_Widget_Text');
unregister_widget('WP_Widget_Categories');
unregister_widget('WP_Widget_Recent_Posts');
unregister_widget('WP_Widget_Recent_Comments');
unregister_widget('WP_Widget_RSS');
unregister_widget('WP_Widget_Tag_Cloud');
unregister_widget('WP_Nav_Menu_Widget');
}
add_action('widgets_init', 'unregister_default_widgets', 11);

Install and activate the Code Snippets plugin, then navigate to Snippets > Add New:

Adding a new snippet to the Code Snippets plugin.

Here, add a descriptive name and paste in the code above:

Adding the snippet to remove default widgets to the Code Snippets plugin.

Then click on the Save Changes and Activate button at the bottom of the screen. After the snippet is activated, your Widgets page might look more like this:

Widget page with no default widgets.

The code removes only the default widgets listed in the snippet. You can keep any default widget by deleting its corresponding line of code.

2. Protect your website from malicious attacks

Malicious attacks can happen to any website. Security plugins can protect you to an extent, but they’re not without their faults. Plus, they can be accidentally deactivated by your clients, leaving websites vulnerable. Clients will have a harder time removing code snippets.

The security features offered by code snippets are not usually as robust as plugins or other tools. However, this one can reject all malicious URL requests:

global $user_ID; if($user_ID) {
if(!current_user_can('administrator')) {
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")) {
@header("HTTP/1.1 414 Request-URI Too Long");
@header("Status: 414 Request-URI Too Long");
@header("Connection: Close");
@exit;
}
}
}

Simply add a new snippet like we described above and paste it in as you see below:

Code snippet in the plugin interface.

Although it’s not comprehensive, taking a variety of precautions can improve your security strategy can prevent your client sites from devastating attacks.

3. Email contributors when publishing their posts

When publishing posts from contributors, it’s courteous to alert them via email. When carried out manually, this extra step in website management can become time-consuming and annoying. This is especially true for sites with highly active blogs.

Fortunately, you can automate this process. This code snippet sends an email to each contributor when you publish a post they wrote. It uses the data from the author profile and a predetermined message set out in the code:

function wpr_authorNotification($post_id) {
$post = get_post($post_id);
$author = get_userdata($post->post_author);

$message = "
Hi ".$author->display_name.",
Your post, ".$post->post_title." has just been published. Well done!
";
wp_mail($author->user_email, "Your article is online", $message);
}
add_action('publish_post', 'wpr_authorNotification');

Your resulting contributor email might look something like this:

Email sent to contributor when post is published.

The code snippet sends the email as soon as the post is published. If you want to send a longer email, you can simply adjust the message in the code. The Code Snippets plugin makes this easy, as you can quickly edit any snippet.

Just navigate to Snippets > All Snippets and click on the Edit link below your contributor email notification snippet:

Editing a snippet in the Code Snippets plugin.

In the editor, update the email’s content:

Saving changes to a snippet.

Finally, click on the Save Changes button to implement your new message.

4. Prevent clients from deactivating specific plugins

Most developers have specific plugins they install on all their client websites. Your clients may not realize the importance of one and deactivate it. This could break key functionality of their website or cause other trouble you’ll have to fix.

You can remove your clients’ ability to disable specific plugins with this code snippet:

add_filter( 'plugin_action_links', 'disable_plugin_deactivation', 10, 4 );
function disable_plugin_deactivation( $actions, $plugin_file, $plugin_data, $context ) {

if ( array_key_exists( 'deactivate', $actions ) && in_array( $plugin_file, array(
'woocommerce/woocommerce.php'
)))
unset( $actions['deactivate'] );
return $actions;
}

This code is ideal for protecting crucial plugins. If the plugin is not listed in the code, your clients can still deactivate it.

However, those listed will no longer have Deactivate links on the Plugins page in your dashboard, like WooCommerce in the image below:

Plugin menu with deactivation option disabled.

In the event that you ever need to deactivate one of these plugins for troubleshooting purposes, you can easily do so by disabling this snippet. Just toggle the switch next to it in the Code Snippets list to the ‘off’ position:

Disabling a snippet in the Code Snippets plugin.

You can then navigate back to the Plugins page, take care of whatever issue you need to handle, and turn the snippet on again when you’re finished.

5. Change the default Gravatar

When users leave comments on a WordPress site, their post will include a profile photo via Gravatar. The default icon for users who haven’t set up their Gravatar account is a ‘Mystery Person’.

However, this isn’t the best option for all websites. WordPress has some other default avatars you can choose from in your Discussion settings, but for branding purposes, your clients may want custom ones instead:

The default Gravatar options in WordPress.

To use a custom image, you need to add a code snippet to your site. First, upload the image to your Media Library. Then add the following code snippet:

add_filter( 'avatar_defaults', 'wpb_new_gravatar' );
function wpb_new_gravatar ($avatar_defaults) {
$myavatar = 'http://example.com/wp-content/uploads/2017/01/wpb-default-gravatar.png';
$avatar_defaults[$myavatar] = "Default Gravatar";
return $avatar_defaults;
}

The URL in the third line above should be the URL for the image you want to use. You can find it by opening the file in your Media Library.

After adding the code snippet, your new Gravatar will appear under the name “Default Gravatar”. You can select it in Settings > Discussion:

Gravatar menu with new default Gravatar.

Make sure to save the changes to your settings.

Conclusion

Expanding the functionality of your clients’ websites and improving your workflow with code snippets is possible, but adding them to your functions.php file could cause trouble. The Code Snippets plugin makes it easier to incorporate and manage them.

Five reasons to use code snippets in your WordPress development include:

  1. To remove default widgets from client sites.
  2. For protection against malicious attacks.
  3. So you can automatically email contributors when publishing their posts.
  4. To prevent clients from deactivating specific plugins.
  5. If you want to change the default Gravatar.

Do you have any questions about using code snippets in your WordPress development? Ask away in the comments below!

Image credit: Pexels.

Will Morris

Will Morris is a staff writer at WordCandy.co. When he's not writing about WordPress, he likes to gig his stand-up comedy routine on the local circuit.

3 Comments

  1. WPSlash

    Just perfect article..
    I will definitely point some of my customers to this post , as a lot of them struggling with adding hooks .

  2. tanishq

    This 5 code snippets will be very helpful for the sites on wordpress.
    Thankyou!

  3. Somnath

    The concept of snippets is mostly unknown to website owners. Your article definitely stresses the importance of snippets as a part of the website performance which webmasters should implement

Leave a Reply

Your email address will not be published. Required fields are marked *

Over 65,000 WordPress professionals are already using ManageWP

Add as many websites as you want for free, no credit card required. Sign up and start saving time!

Have questions? Get in touch!

Over 65,000 WordPress professionals are already using ManageWP

Add as many websites as you want for free, no credit card required. Sign up and start saving time!



Have questions? Get in touch!

Over 65,000 WordPress professionals are already using ManageWP

Add as many websites as you want for free, no credit card required. Sign up and start saving time!



Have questions? Get in touch!

Over 65,000 WordPress professionals are already using ManageWP

Add as many websites as you want for free, no credit card required. Sign up and start saving time!



Have questions? Get in touch!