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 [email protected] with @wpkube.

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


Adding Shortcodes to Widgets

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

1 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.

1 function wps_registration_redirect(){
2 return home_url( '/finished/' );
3 }
4 add_filter( 'registration_redirect''wps_registration_redirect' );


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.

1 if (!defined('WP_POST_REVISIONS')) define('WP_POST_REVISIONS', 5);
2 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].

1 function year_shortcode() {
2 $year date('Y');
3 return $year;
4 }
5 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.

1 function the_title_trim($title) {
3 $title = attribute_escape($title);
5 $findthese array(
6 '#Protected:#',
7 '#Private:#'
8 );
10 $replacewith array(
11 ''// What to replace "Protected:" with
12 '' // What to replace "Private:" with
13 );
15 $title = preg_replace($findthese$replacewith$title);
16 return $title;
17 }
18 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.

1 Posted on <?php the_time('F jS, Y') ?>
2 <?php
3           $u_time = get_the_time('U');
4           $u_modified_time = get_the_modified_time('U');
6       if ($u_modified_time != $u_time) {
7                 echo "and last modified on ";
8                 the_modified_time('F jS, Y');
9                 echo ". ";
10           }
11 ?>


Remove the WordPress Version Number

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

1 <?php
2 // Remove the version number of WP
3 // Warning - this info is also available in the readme.html file in your root directory - delete this file!
4 remove_action('wp_head''wp_generator');
5 ?>

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.

1 // Hide WordPress Update
2 function wp_hide_update() {
3 remove_action('admin_notices''update_nag', 3);
4 }
5 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.

1 function remove_comment_fields($fields) {
2 unset($fields['url']);
3 return $fields;
4 }
5 add_filter('comment_form_default_fields','remove_comment_fields');


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.

1 add_filter('manage_posts_columns''posts_columns_attachment_count', 5);
2 add_action('manage_posts_custom_column''posts_custom_columns_attachment_count', 5, 2);
4 function posts_columns_attachment_count($defaults){
5 $defaults['wps_post_attachments'] = __('Attached');
6 return $defaults;
7 }
8 function posts_custom_columns_attachment_count($column_name$id){
9 if($column_name === 'wps_post_attachments'){
10 $attachments = get_children(array('post_parent'=>$id));
11 $count count($attachments);
12 if($count !=0){echo $count;}
13 }
14 }


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.

1 add_filter( 'jpeg_quality''smashing_jpeg_quality' );
2 function smashing_jpeg_quality() {
3 return 100;
4 }

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.

1 add_action('save_post''wpds_check_thumbnail');
2 add_action('admin_notices''wpds_thumbnail_error');
4 function wpds_check_thumbnail($post_id) {
6 // change to any custom post type
7 if(get_post_type($post_id) != 'post')
8 return;
10 if ( !has_post_thumbnail( $post_id ) ) {
11 // set a transient to show the users an admin message
12 set_transient( "has_post_thumbnail", "no" );
13 // unhook this function so it doesn't loop infinitely
14 remove_action('save_post''wpds_check_thumbnail');
15 // update the post set it to draft
16 wp_update_post(array('ID' => $post_id'post_status' => 'draft'));
18 add_action('save_post''wpds_check_thumbnail');
19 else {
20 delete_transient( "has_post_thumbnail" );
21 }
22 }
24 function wpds_thumbnail_error()
25 {
26 // check if the transient is set, and display the error message
27 if ( get_transient( "has_post_thumbnail" ) == "no" ) {
28 echo "
29 <div id="message" class="error">
31 You must select Featured Image. Your Post is saved but it can not be published.
33 </div>
34 ";
35 delete_transient( "has_post_thumbnail" );
36 }
38 }


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:

1 function replace_howdy( $wp_admin_bar ) {
2 $my_account=$wp_admin_bar->get_node('my-account');
3 $newtitle str_replace'Howdy,''Logged in as'$my_account->title );
4 $wp_admin_bar->add_node( array(
5 'id' => 'my-account',
6 'title' => $newtitle,
7 ) );
8 }
9 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.

1 function exclude_category_home( $query ) {
2 if $query->is_home ) {
3 $query->set( 'cat''-5, -34' );
4 }
5 return $query;
6 }
8 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.

1 function limit_posts_per_search_page() {
2     if ( is_search() )
3         set_query_var('posts_per_archive_page', 20);
4 }
6 add_filter('pre_get_posts''limit_posts_per_search_page');

Source: WordPress

Leave a Reply