Get $500+ of the best After Effects files, video templates and music for only $20!
Quick Tip! 9 Handy WordPress Code Snippets (That You Really Should Know!)

Quick Tip! 9 Handy WordPress Code Snippets (That You Really Should Know!)

Tutorial Details
  • Program: WordPress
  • Version: 3.0+
  • Difficulty: Beginner
  • Estimated Completion Time: 30 minutes

Here are some short but handy code snippets that may make your life as a WordPress developer a little easier. We’ll cover a little bit of everything, from how to automatically delete posts, how to quickly dish out a post thumbnail, to how to redirect users once they’ve logged in. Open up your text-replacement program and get ready to add a few new shortcuts!

We’ll start off with a few simple one-liners.


1. Hide The Front-End Dashboard Bar

Since v3.1, WordPress has provided a front-end admin bar for all users. Depending on your intent, this can detract from the look of your site. To disable it, use the show_admin_bar function:

show_admin_bar(FALSE);

You can also disable this from your User Profile, but this is especially useful if you’ve got a ton of authors/members on the site and you need to disable the bar altogether.


2. Empty Trashed Posts Automatically

Trashed posts can build up if you forget to delete them permanently. Use this code in /wp-config.php to empty your trashed posts:

define('EMPTY_TRASH_DAYS', 5 );

3. Turn On WordPress Internal Debugger

When you’re developing, you need to see the errors your code is throwing up. Keep in mind that not all errors stop a script from executing but they are errors nevertheless, and they may have strange effects upon your other code. So, turn on WordPress debug by placing this in your /wp-config.php:

define('WP_DEBUG', TRUE);

You may be amazed by what you see in the footer. Remember to turn debugging off when your site is ready to go public. Debug info can be valuable to hackers.


4. Redirect Users After They Login

When a user logs in, they normally get sent straight to their dashboard. This may not be the experience you want your users to have. The following code uses the login_redirect filter to redirect non-administrators to the home page:

add_filter("login_redirect", "subscriber_login_redirect", 10, 3);

function subscriber_login_redirect($redirect_to, $request, $user){  

  if(is_array($user->roles)){

    if(in_array('administrator', $user->roles)) return home_url('/wp-admin/');

  }

  return home_url();

}

Based on the user’s role, you could send them to any page you like.


5. Show A Default Post Thumbnail Image

Since v2.9, WordPress has provided a post thumbnail image option, just like the images you see here on wp.tutsplus. On the admin post page it’s called ‘Featured Image’. But if you don’t have an image for your post, you can simply call a default image.

Within the loop:

if(has_post_thumbnail()){

  the_post_thumbnail();

}else{

  echo '<img src="' .  get_bloginfo('template_directory') . '/images/default_post_thumb.jpg" />';

}

You could even have a bunch of default images and pick one at random


6. Show “Time Ago” Post Time For Posts And Comments

Instead of: Posted on October, 12, 2011, we can have: Posted 2 days ago.

As used in the loop:

echo human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago';
  • human_time_diff() converts a timestamp value to a friendly form
  • get_the_time() gets the time the post was made, with ‘U’ parameter gets value as a Unix timestamp
  • current_time() gets the current time, with ‘timestamp’ parameter gets value as a Unix timestamp

Use it on comments as well:

echo human_time_diff(get_comment_time('U'), current_time('timestamp')) . ' ago';

Or maybe show the regular date/time of the post only if more than a week ago, else show the time ago:

$time_diff = current_time('timestamp') - get_the_time('U');

if($time_diff < 604800){//seconds in a week = 604800

  echo 'Posted ' . human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago';

}else{

  echo 'Posted on ' . get_the_date() . ', ' . get_the_time();

};

7. Style Post Author Comments Differently

It’s nice for users to be able to see when the author of a post makes a comment on the post, just like we do here on wp.tutsplus. All we have to do is add a class to the comment wrapper and then style it in the theme.

In order to find which comments are made by the post author, we use this code to output a class name:

if($comment->user_id == get_the_author_meta('ID')){

  echo '<div class="comment_wrapper author_comment">';

}else{

  echo '<div class="comment_wrapper">';

}

We compare the user ID of the comment with the post author ID from get_the_author_meta. If they match, we echo a class of author_comment which we can then style with css.


8. Show User, Post And Comment Info For Your WordPress Site

You can query your WordPress database directly to show handy site info. Put this function in your functions.php and call it anywhere in your template files with get_site_data()

function get_site_data(){

  global $wpdb;

  $users = $wpdb->get_var("SELECT COUNT(ID) FROM $wpdb->users");

  $posts = $wpdb->get_var("SELECT COUNT(ID) FROM $wpdb->posts WHERE post_status = 'publish'");

  $comments = $wpdb->get_var("SELECT COUNT(comment_ID) FROM $wpdb->comments");

  echo '<p>' . $users . ' members have made ' . $comments . ' comments in ' . $posts . ' posts</p>';

}

This is better than calling some of the native WordPress functions as it counts all post types and only currently published posts.


9. Add A JavaScript File Correctly

WordPress gives us the wp_enqueue_script function so we can add scripts safely.

Say we have a scripts dir under our template dir, and in there we have a script called do_stuff.js. So we have url_to_template_dir/scripts/do_stuff.js

Let’s include our script the right way. This must be included before the wp_head call in your header file:

$script_url = get_template_directory_uri() . '/scripts/do_stuff.js'; 

wp_enqueue_script('do_stuff', $script_url);

Here we concatenate our script path and name onto the output of the WordPress get_template_directory_uri function. We then enqueue the script by providing a handle (for possible later reference) and the url to our script. WordPress will now include our script in each page.

The real advantage to all of this is that, say our do_stuff script was a jQuery script, then we would also need to have jQuery loaded.

Now, jQuery is included by default in WordPress, and has been pre-registered with the handle jquery. So all we need do is enqueue our jQuery, then enqueue our do_stuff.js, like this:

wp_enqueue_script('jquery');

$script_url = get_template_directory_uri() . '/scripts/do_stuff.js'; 

wp_enqueue_script('do_stuff', $script_url, array('jquery'));

Note the third parameter to wp_enqueue_script for do_stuff: that tells WordPress that our do_stuff script is dependent on the file with the handle jquery. This is important because it means that jquery will be loaded before do_stuff. In fact, you could have the enqueue statements in reverse order and it wouldn’t matter since defining a script’s dependencies allows WordPress to put the scripts in correct loading order so that they all work happily together.

Add Comment

Discussion 42 Comments

  1. Callum says:

    Pretty handy snippets. The one to redirect users after login could be very handy for some of my sites. Good work!

  2. Frank Zabotka says:

    Seriously? One more “super awesome 40 cool” post with copied snippets?

    • Brandon Jones says:

      I hear where you’re coming from – but this is actually the first pure code snippet roundup that we’ve posted, and Ross actually put this stuff together based on his own daily workflow because it’s, frankly, fun and useful to see the snippets that other developers use the most. Sometimes it’ll even show you something that you don’t know (I personally didn’t know a few of these). If you read the article (or any of his other posts), you’d know that he isn’t copy/pasting code as you’ve suggested, which is exactly what a short code roundup post like this should be. I’ll agree that other sites that copy/paste each others code aren’t really doing the world a lot of good, but I honestly think that this isn’t one of those. Thanks for the comment Frank!

      • Alex says:

        It would be awesome if you create a section here similar to Snippets on css-tricks for both power users and beginners. So, wp.tutsplus.com can be source not only for great tutorials but collection of snippets as well.

        • Brandon Jones says:

          Funny you should mention this Alex – it’s actually something I’ve had in mind for a while, and that we’ll be rolling out in the future :) I’m a HUGE fan of Chris’ work over there, and the snippets are a great fit for this site now that we’re starting to near our six month mark as a site.

          • That’s what I decided to turn my own website into. A repository of key points and snippets or somewhat advanced code. For my own reference, really. I create turorials out of them to help others, but also because I might need a snippet or specific functionality 2 years down the road and completely forget how I did it before.

            Considering I generally heavily comment my code to aid in longevity and memory for future updates I realized that good commenting, in itself, is quite like writing a tutorial…so it begins on my website with code I use in my workflow.

            Now If wp.tuts.plus can weed out the articles and tutorials to include edited, tested, and working code that won’t confuse people when it pulls up errors immediately (when not modified, but as is in the tutorials) then you’ll be perfectly ready for the snippet repository similar to catswhocode.

            Just please, for the community and your own standing in it (the WP community that is) edit the articles, codes and snippets for accuracy before making them public! Most beginner coders who use your site aren’t familiar with proper and effective debugging techniques!

  3. Ross Thank you for the handy wordpress snippets.

  4. Rick says:

    Hi,

    In the redirect snippet the filter should match the function’s name:

    subscriber_login_redirect -> wp_demo_login_redirect

    Great tips !

  5. fakenpro says:

    in 4 snippets name of function is diferent of name function that used in filter, maybe error

  6. Chris says:

    What still sucks (and will get better in 3.3) is, that wp_enqueue_script always places scripts in the header, which can be problematic when talking about performance.

    • Brandon Jones says:

      Agreed! Getting scripts into the footer is a real pain at the moment – it’s possible, but it’s not the easiest to sort out :

      wp_register_script( 'prettyPhoto', WP_THEME_URL . '/assets/javascripts/jquery.prettyPhoto.js', false, null, true);
      wp_enqueue_script( 'prettyPhoto' );

  7. Antonio says:

    Hello and thanks for the code!

    One question, how do you enqueue javascript with parameters in {} like this one??

    {lang: ‘es’}

    BR

    • Ross Elliot says:
      Author

      Antonio, I’m not quite sure this is what you mean, but WordPress can drop data onto the page that you can then access in your scripts. You use the wp_localize_script function for that.

      As per the example in #9 above:

      wp_enqueue_script(‘do_stuff’, $script_url);

      $data = array(‘name’ => ‘ross’, ‘gender’ => ‘male’);

      wp_localize_script(‘do_stuff’, ‘do_stuff_data’, $data);

      That will create a do_stuff_data object on the page wrapped in script and CDATA tags, like this:

      <script type=’text/javascript’>
      /* <![CDATA[ */
      var do_stuff_data = {
      name: "ross",
      gender: "male"
      };
      /* ]]> */
      </script>

      You’ll then be able to access that data as an object in your scripts. So, you could do:

      alert(do_stuff_data.name + ‘ is a ‘ + do_stuff_data.gender);

      That would alert: ross is a male

      Of course, the real power here is that the data array can be created dynamically from any source, such as a database query.

      Hope that helps.

      • Antonio says:

        Thanks Elliot for the info. My question was for the Google+ button code and languages.

        http://www.google.com/intl/es/webmasters/+1/button/index.html

        <!– Añade esta etiqueta en la cabecera o delante de la etiqueta body. –>
        <script type=”text/javascript” src=”https://apis.google.com/js/plusone.js”>
        {lang: ‘es’}
        </script>

        <!– Añade esta etiqueta donde quieras colocar el botón +1 –>

        I don’t own the script and have to pass the lang:es property to it.

        Do you know how to use wp_script_enqueue in this case??

        Thanks a lot again and regards

        • Ross Elliot says:
          Author

          Sorry, Antonio, I don’t speak Spanish!

          But it looks like the data is in json format so you should be able to access that in your script.

          Ross

          • Antonio says:

            Thanks and excuse me for asking again. Lets try to clarify

            For inserting Google+ button we have to insert the following in the header

            {lang: ‘es’}

            then just add this where we want the button to appear

            So the point is to use something like

            wp_enqueue_script(‘plusone’, https://apis.google.com/js/plusone.js);

            Following your indications, would the following be correct?

            wp_enqueue_script(‘plusone’, https://apis.google.com/js/plusone.js);
            $data = array(‘lang’ => ‘es’);
            wp_localize_script(‘plusone’, ‘plusone_data’, $data);

            and then

            using in the desired place??

            Thanks again

          • Ross Elliot says:
            Author

            Antonio, that’ll work just fine.

            Don’t forget to put the script url in quotes.

            Then you can use the data in your scripts like: plusone_data.lang

  8. EmpreJorge says:

    Nice collection :D , thanks
    PS: I use <?php comment_class(); ?> to style post author comments differently

  9. Abhimanyu says:

    Amazing to see what we can achieve from an open source like WordPress!
    Will be immediately using 5 out of 9. :)

  10. ryanve says:

    In #9 the “dependencies” need to be in an array (even if there is only one):

    wp_enqueue_script( ‘do_stuff’, $script_url, array( ‘jquery’) );

  11. Piet says:

    Great tips, but why oh why no i18n at all???

    Don’t you think it is about time, especially for a site like yours, to properly implement i18n in all of your online code?

  12. Great tips, the function name in number 4 differs from the filter name though.

  13. Chip Bennett says:

    Nice list!

    But, I’m curious: why the extra code just to determine if a comment is from the post author? If the Theme is using wp_list_comments() with the default output, or with a callback that calls comment_class(), or stand-alone comment-list markup (but nobody uses that anymore, right?) that calls comment_class(), then styling author comments is no more difficult than targeting the .bypostauthor class.

  14. Everytime I see a post with a title like this I check it out just to see if it’s another repetitive mashup of commonly known pieces of code.
    I recognize most of those (altough they’re written in a different way) but what really got me by surprise is the Internal Debugger. get_site_data is nice stuff too.
    Now the author comment snippet is a bit clumsy as Chip remarked above.
    I like Wp Tuts overall, congratulations.

  15. Ross Elliot says:
    Author

    Thanks for all the comments.

    Sure, there’s lots of snippets posts on the web, but as Brandon mentioned above, I put together this list because I use these regularly. And as a few of you mentioned, despite being familiar with some of them, there’s the odd snippet that you found worthwhile.

    A word about repetition. There’s only so many ways to skin a cat and it shouldn’t be surprising that with a finite number of WordPress functions and millions of WordPress sites and their attendant developers, that we see similar solutions to the same problems. Frankly, if I could recall every great snippet I ever saw, I’d be a much better programmer. Scanning roundups can be a wonderful aid to memory.

    Thanks for the heads-up about comment author styling.

  16. very cute snippet. if you have the demos, it will be better.

  17. Connor Crosby says:

    At first, I thought this would be a normal snippets post where they shared the usual ones. But, to my surprise, you actually have great stuff! These are going to be very helpful and I thank you very much for sharing them :)

    Now where were you a few months ago ;)

  18. waqas says:

    Great Collection! Keep it up

  19. Chandu says:

    #1. Hide admin bar is the one i am going to put it in right now. It takes so much time to load just that :S.

    And as a beginner i always love to have a look on these kinds of roundup snippets. Thanks

  20. cory says:

    These snippets are going to save me time, thanks

  21. Malika says:

    Can someone help me with a WordPress code edit I need? I have a site for which I’ve added a section of featured posts that scroll across the top of the page. In order for the post to be included in this section it must have a “featured image” set. The problem is that when I select the featured image, it throws off the look of the individual post. See sample of what I mean in this post: http://atlanta-restaurantblog.com/2011/10/tavern-99-buckhead-atlanta-ga/

    So, what I’d like to know is, is there a way to modify the CSS to set an image as the featured image so it shows up in the scroll across the screen but not in the individual post itself?

    Thank you

    • Chris M. says:

      Hey Malika…

      Not sure if you still need help, but could I use the contact form for the site to get in touch with you? I will see what I can do.

  22. CiNiTriQs says:

    Thank you very much for this, I just found one I need in an theme update later on. Some I didn’t use yet as well, nice, keep em coming!

  23. Great post. indispensable. Thanks

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.