• Categories
    • Tutorials
    • Beginners Guide
    • WordPress News
    • WordPress Security
    • Best WordPress Plugins
    • WordPress Themes
    • Product Reviews
    • WP Tips & Tricks
  • Guides
    • Start a Blog
    • Make a Website
    • WordPress Hosting
  • WordPress Hosting
    • A2 Hosting
    • HostGator
    • Bluehost
    • Cloudways
  • Managed Hosting
    • WPEngine
    • Rocket.net
    • WPX
    • Kinsta
  • Coupons
    • WPEngine
    • Flywheel
    • Cloudways
    • A2 Hosting
    • WPX Hosting
WordPress Tips & Tricks

16 Useful Code Snippets for WordPress

Last Updated on: January 27, 2016 Daryn Collier 8 Comments

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.

+ Share
Disclosure

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.

Related Posts

Back to all articles
  • WordPress XML Files: What They Are and How to Open Them

    WordPress XML Files: What They Are and How to Open Them

  • WordPress’ Settings: A New User’s Checklist

    WordPress’ Settings: A New User’s Checklist

  • Introducing The Wp-Config.Php File For WordPress

    The wp-config.php File: Why It’s the Most Important File For WordPress

Coupons

View more deals
  • 10% OFF

    Elegant Themes Coupon

    You can’t move within WordPress circles without coming across E
    Get This Deal
  • pressable logo
    15% OFF

    Pressable Coupon

    If you’re looking for a high-quality managed WordPress hosting
    Get This Deal
  • Teachable Coupon Code
    10% OFF

    Teachable Coupon

    Building an online course business requires the right platform to
    Get This Deal
8 Comments Leave a Reply
  1. Patrick Boudewijn says

    September 9, 2015 at 6:01 pm

    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!

    Reply
  2. chris says

    September 12, 2015 at 8:49 pm

    Very helpful article!!

    Reply
  3. Sherryl Perry says

    September 14, 2015 at 2:50 am

    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.

    Reply
    • Daryn Collier says

      September 14, 2015 at 3:19 am

      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

      Reply
    • Devesh Sharma says

      September 17, 2015 at 4:51 pm

      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!

      Reply
  4. Donald says

    September 27, 2015 at 11:22 am

    You Guys ( and Gals ) are doing a great job bringing useful informaton to the people who need it!

    Thanks!

    Reply
  5. Andre says

    July 24, 2016 at 5:43 pm

    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!

    Reply
    • Dev says

      July 28, 2016 at 3:15 am

      No problem, Andrew. Glad you found the post useful.

      Hope to see you around.

      Reply

Leave a Reply Cancel reply

Full Disclosure This post may contain affiliate links, meaning that if you click on one of the links and purchase an item, we may receive a commission (at no additional cost to you). All opinions are our own and we do not accept payments for positive reviews.

Our Newsletter

Get awesome content delivered straight to your inbox.

Thank you!

You have successfully joined our subscriber list.

.

THE BEST OF WPKUBE

Some of the best content we have published so far.

BEGINNER GUIDES & REVIEWS

110 Best WordPress Hosting Options for 2025 (Pros & Cons)
28 Best Managed WordPress Hosting Providers for 2025 Compared
38 Best Cheap WordPress Hosting Providers in 2025 (From $1.99)
46 Best WordPress LMS Plugins – Detailed Comparison & Review for 2024
55 Best WooCommerce Hosting Providers Compared in 2024 (All Budgets)
66 Best WordPress Landing Page Plugins Compared + Recommendations (2024)
79 Best List Building Plugins for WordPress In 2024
8How to Fix the 500 Internal Server Error on Your WordPress Website
9Beaver Builder Review: Honest Thoughts + Pros and Cons (2025)
10OptimizePress Review: Create Landing Pages with Ease
11How to Make a Website: Complete Beginner’s Guide
12Top 22 Best Free Stock Photo Resources For Your Site
13How to Start a Blog in 2022 (Step by Step Guide)
14How To Fix ‘503 Service Unavailable’ WordPress Error
1511 Best Contact Form Plugins for WordPress in 2025
16How to Add a Custom Logo to Your WordPress Site
17How to Fix Error Establishing a Database Connection in WordPress

WPEngine: 50% OFF Deal

Save 50% on one of the best managed hosting providers.

Get this Deal
Featured In Forbes Huffpost Entrepreneur SEJ

About WPKube

WPKube is an online WordPress resource which focuses on WordPress tutorials, How-to’s, guides, plugins, news, and more. We aim to provide the most comprehensive beginner’s guides to anything about WordPress — from installing plugins, themes, automated installs and setups, to creating and setting up pages for your website.

We have over 500+ tutorials, guides, product reviews, tips, and tricks about WordPress. Founded by Devesh Sharma, the main goal of this site is to provide useful information on anything and everything WordPress.

Twitter Facebook

Useful Links

  • Behind the Scenes
  • Beginner Guides
  • WordPress Hosting
  • WooCommerce Themes
  • MeridianThemes
  • Exclusive WordPress Deals
View All Guides »

Reviews

  • WPEngine 33% OFF
  • WPX Hosting
  • Flywheel 33% OFF
  • Divi Theme 20% OFF
  • Systeme.io
  • Elegant Themes
Reviews »

Deals

  • InMotion Hosting
  • LifterLMS Coupon
  • LiquidWeb Coupon
  • WPEngine Coupon
  • A2 Hosting
  • Solid Affiliate
More Deals »
© Copyright 2023 WPKube ® All Rights Reserved.
  • Contact
  • Site Terms
  • Disclosure
  • Privacy Policy