16 Useful Code Snippets for WordPress

It’s the little things that make a difference, right? That’s part of what makes WordPress so great – the number of ways in which it can be customized to meet your specific needs is virtually limitless.

Sure you can find plugins to meet just about every need imaginable but if you can find a simple snippet to get the job done, it’s usually the path of least resistance.

We’ve put together a collection of useful snippets from around the web, all of which can make your life with WordPress just a little bit easier and more functional.

Using Code Snippets

There are a few different ways to use code snippets. Most of the time, you’ll find yourself heading to the functions.php file but give that some extra thought.

Your functions.php file is very specific to your theme. If you decide to change themes down the road and have functions that are non-theme specific, you’ll have to start from scratch. Also, if you make changes to your parent theme and then update, all your changes will be overwritten. Make sure you’re using a child theme.

To get around this problem you’re left with a few choices:

  1. Write a custom plugin.
  2. Use a snippet plugin like Code Snippets.
  3. Use a theme specific plugin.
  4. Use a child theme and put all function changes in the child theme.

A free plugin like code-snippets will allow you to create your own customized repository of snippets that can be activated or deactivated as required without having to mess around with your functions.php file.

There are other solutions as well, for example if you’re running a Genesis theme, you could use the Genesis Extender Plugin from Cobalt Apps which allows you to add custom Functions through the plugin back-end. This particular plugin also lets you stop the custom functions from affecting the WordPress admin area. This can prevent breaking your entire site (at least the back-end anyways) – we’ve all experienced this at some point in time right?

The final piece of advice, before we jump into the good stuff, is to always back up your site before you start making changes – especially make sure you have a copy of your original functions.php file handy.

Automatic Linking to Twitter Usernames

Anytime you mention a company or individual from within a post it’s nice to link to their Twitter profile. This handy little snippet will watch your posts for text that signifies a Twitter username and then automatically create a link for you. Conveniently replacing no-link-@wpkube with @wpkube.

function content_twitter_mention($content) {
return preg_replace('/([^a-zA-Z0-9-_&])@([0-9a-zA-Z_]+)/', "$1@$2", $content);
}
add_filter('the_content', 'content_twitter_mention');
add_filter('comment_text', 'content_twitter_mention');

Source: WPSNIPP

Adding Shortcodes to Widgets

Sometimes you just want add shortcodes to a text widget. Luckily, this is a simple one line solution.

add_filter( 'widget_text', 'do_shortcode' );

Source: Thomas Griffin

Redirect New Registered Users to a Specific Page

If you require a new user to register on your WordPress site, you might want to redirect them to a specific page upon successful completion. Maybe you want to provide them with some important information or specific download.

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

Source: WPSNIPP

Limiting WordPress Post Revisions

Keeping track of post revisions in WordPress is a great feature – to a certain extent. If you do much editing within the WordPress editor it’s easy to end up with dozens or even hundreds of revisions stored in the database. An easy fix is to limit the number of revisions per post to something more reasonable like 3-5.

if (!defined('WP_POST_REVISIONS')) define('WP_POST_REVISIONS', 5);
if (!defined('WP_POST_REVISIONS')) define('WP_POST_REVISIONS', false);

Source: WP-Functions

Using the Current Year in Your Posts

Do you ever wish you could insert the current year in some of your posts via a simple shortcode?
Add the snippet below to your functions.php file and you’ll be partying like it’s [year].

function year_shortcode() {
$year = date('Y');
return $year;
}
add_shortcode('year', 'year_shortcode');

Source: CSS-Tricks

Remove the Private/Protected From Your Post Titles

In case you ever publish posts that are private, you’ll notice that the title is prefaced by an unsightly reminder. You can add the code below to your functions file and everything will look good again.

function the_title_trim($title) {

$title = attribute_escape($title);

$findthese = array(
'#Protected:#',
'#Private:#'
);

$replacewith = array(
'', // What to replace "Protected:" with
'' // What to replace "Private:" with
);

$title = preg_replace($findthese, $replacewith, $title);
return $title;
}
add_filter('the_title', 'the_title_trim');

Source: CSS-Tricks

Show a Post Date and Modified Date

Sometimes six months after you write a post you decide to update it with some new information. This simple snippet will add a modified date to your posts in the event that you make a change sometime after the initial publication date.

Posted on <?php the_time('F jS, Y') ?>
<?php
          $u_time = get_the_time('U');
          $u_modified_time = get_the_modified_time('U');

      if ($u_modified_time != $u_time) {
                echo "and last modified on ";
                the_modified_time('F jS, Y');
                echo ". ";
          }
?>

Source: WPSNIPP

Remove the WordPress Version Number

In case you want to hide your WordPress version number, from visitors just add this short snippet.

<?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');
?>


Source: WPFunction

Hide the WordPress Update Message

When managing client websites, sometimes you want to delay updating to the latest version of WordPress until you’ve had a chance to create a new backup. This snippet will hide the tempting update message that shows up in the header.

// Hide WordPress Update
function wp_hide_update() {
remove_action('admin_notices', 'update_nag', 3);
}
add_action('admin_menu','wp_hide_update');

Source: Torque Mag

Remove the Comment URL Field

If your blog is continually the target of spammers, you can remove the URL field from comments which takes away most of their motivation.

function remove_comment_fields($fields) {
unset($fields['url']);
return $fields;
}
add_filter('comment_form_default_fields','remove_comment_fields');

Source: wphub.com

Wondering How Many Images an Author Has Attached to a Post?

When authors are responsible for adding their own images to a post, it’s nice to know how may have been attached with a quick glance. This snippet adds a custom admin column.

add_filter('manage_posts_columns', 'posts_columns_attachment_count', 5);
add_action('manage_posts_custom_column', 'posts_custom_columns_attachment_count', 5, 2);

function posts_columns_attachment_count($defaults){
$defaults['wps_post_attachments'] = __('Attached');
return $defaults;
}
function posts_custom_columns_attachment_count($column_name, $id){
if($column_name === 'wps_post_attachments'){
$attachments = get_children(array('post_parent'=>$id));
$count = count($attachments);
if($count !=0){echo $count;}
}
}

Source: WPSNIPP

Put an End to Automatic JPEG Compression

If you’re using a third-party image optimizer like Optimus or WP Smush, you might decide you want to disable the built-in WordPress image optimizer which is set to 90% out of the box.

add_filter( 'jpeg_quality', 'smashing_jpeg_quality' );
function smashing_jpeg_quality() {
return 100;
}

Source: SmashingMagazine

Require a Featured Image

This is a great idea if you have clients who are creating their own posts. After you spend time devising an attractive template layout, clients often decide to skip the featured image, ruining the flow and presentation of what you’ve created. This snippet will require the author to select a featured image before the post can be published.

add_action('save_post', 'wpds_check_thumbnail');
add_action('admin_notices', 'wpds_thumbnail_error');

function wpds_check_thumbnail($post_id) {

// change to any custom post type
if(get_post_type($post_id) != 'post')
return;

if ( !has_post_thumbnail( $post_id ) ) {
// set a transient to show the users an admin message
set_transient( "has_post_thumbnail", "no" );
// unhook this function so it doesn't loop infinitely
remove_action('save_post', 'wpds_check_thumbnail');
// update the post set it to draft
wp_update_post(array('ID' => $post_id, 'post_status' => 'draft'));

add_action('save_post', 'wpds_check_thumbnail');
} else {
delete_transient( "has_post_thumbnail" );
}
}

function wpds_thumbnail_error()
{
// check if the transient is set, and display the error message
if ( get_transient( "has_post_thumbnail" ) == "no" ) {
echo "
<div id="message" class="error">

You must select Featured Image. Your Post is saved but it can not be published.

</div>
";
delete_transient( "has_post_thumbnail" );
}

}

Source: WPSNIPP

Replace the “Howdy, User Name” With Anything You Desire

Not everybody is a western fan. If that include you, maybe it’s time to change the “Howdy” message that appears in the header for logged in users. Something more appropriate might be in order such as “You’re being watched”. Maybe that’s a little creepy – perhaps a simple “Welcome” or a “Logged in as” would be more appropriate. Add the code below to your functions.php:

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 );

Source: Snipplr

Remove or Hide Categories From the Homepage

Sometimes you want to remove or avoid displaying certain categories on your home page. Some premium themes have this function built in so be sure to check your theme settings first. Failing that this little snippet should do the trick.


function exclude_category_home( $query ) {
if ( $query->is_home ) {
$query->set( 'cat', '-5, -34' );
}
return $query;
}

add_filter( 'pre_get_posts', 'exclude_category_home' );

Source: WP Mayor

Show X Results on the Search Results Page

If you want to change the default number of search results returned to something greater or less that the default this snippet will let you do just that.

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');

Source: WordPress

If you have a favorite WordPress snippet that you like to use please share it in the comments below.

Daryn Collier

Daryn Collier is a digital marketer and writer for hire. He is passionate about working with other entrepreneurs who are committed to growing their businesses through inbound marketing. A husband, father and avid CrossFitter, when he’s not working or spending time with his family, he has a love for the barbell and lifting things that are heavy.

View Comments

  • A very useful article you've wrote guys. I will try some of your code snippets especially the one with the Featured image.
    My users always forget to add a featured image and this code you've shared comes at a great time because I wanted to contact my host so they can provide me with a similar solution.
    Great work Daryn!

  • Hi Daryn and welcome to Devesh's blog. I'm a frequent visitor here but I honestly don't comment much. I have to tell you that this is one of the most useful bog posts that I've read all week. Just the link to the code snippets plugin alone is valuable.

    I'm using a premium theme that has a lot of functionality built in. Even so, I have bookmarked this post because four of your snippets will lend themselves perfectly to either one of my blogs or a client site.

    Thanks so much for the information. I just followed you on Twitter. (I've been following Devesh for years now.

    • Thanks Sherryl,
      Glad you found the post useful. I can't take any credit for the snippets though - I just put together the list.

      Daryn

    • Hi Sherryl,

      Thanks so much for the fantastic support all these years. I don't think WPKube could have been where it is today without the support of awesome friends like you :).

      Cheers!

  • It's a bit late of a comment, but I have to say this is an awesome post with snippets, most if not all are real world scenarios that many users will encounter or wish they knew about ahead of time. I design themes, and even I was impressed with your selection of snippets. Cheers!

Recent Posts

10 Best WordPress Website Maintenance and Support Services in 2024

Searching for the best WordPress maintenance service to get a little helping hand with your…

3 months ago

8 Best Managed WordPress Hosting Providers for 2024 Compared

Do you really need managed WordPress hosting? Let's face it: Running a WordPress blog or…

4 months ago

WP Engine Review (2024): Does It Really Make Your Site Faster?

WP Engine is one of the very first companies to start offering tailor-made hosting for…

4 months ago

Cloudways Review (2024): Is This a Good Alternative to Cloud Hosting?

Cloudways is a very original type of a web hosting company when compared to other…

4 months ago

7 Best WordPress Migration Plugins Reviewed and Compared for 2024

WordPress is incredibly easy to install, but if you want to move an already setup…

4 months ago

Divi Theme Review for WordPress: Should You Use It? (2024)

Considering using the Divi theme for your WordPress site? In our hands-on Divi theme review,…

4 months ago