Advertisement
Tips

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

by

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.

Related Posts
  • Code
    Theme Development
    How to Pass PHP Data and Strings to JavaScript in WordPressPhp js 400
    It's good practice to put all your data in static strings in your PHP files. If you need to use some data in JavaScript later on, it's also good practice to put your data as data-* attributes in your HTML. But in some certain scenarios, you have no choice but to pass strings directly to your JavaScript code. If you are including a JavaScript library, and you've found yourself initializing a JavaScript object inside your header.php then assigning data to its properties, then this article is for you. This article will teach you on how to properly pass PHP data and static strings to your JavaScript library.Read More…
  • Code
    Creative Coding
    Using WordPress for Web Application Development: Custom Database QueriesApplication foundation 400
    Throughout this series, we've been looking at the various facilities that make it possible to treat WordPress as a foundation for web application development. Thus far, we've covered a lot of ground: We've talked about how WordPress is more of a foundation rather than a framework. We've discussed the nature of the the Event-Driven Design Pattern. There's been a discussion of Email, User Management, Saving Data, Retrieving Data ...and more. In the most recent articles, we've been talking a look at how to handle queries against the WordPress database through the use of WP_Query and WP_User_Query.Read More…
  • Code
    Creative Coding
    Using WordPress for Web Application Development: Understanding Events, Actions, and FiltersApplication foundation 400
    Throughout this series, we've been taking a look at how WordPress can be used for building web applications. Up to this point, we've established that WordPress is a foundation - rather than a framework - and we've talked a bit about how we need to avoid trying to shoehorn WordPress into another type of design pattern than that of its native type.Read More…
  • Code
    Plugins
    Using HighCharts in WP-AdminHighcharts 400
    Charts are a great way to present data. They make data more digestible by making it visually appealing. In WordPress, there is no built-in method for getting posts and pages data in a graphical form. Although, there are certain plugins available which integrate Google Analytics with WordPress, but they are overkill if you want to get only a portion of that data. Also, nothing should keep you from learning new techniques and to dive straight into the subject is the best way to learn.Read More…
  • Code
    Theme Development
    A Guide to the WordPress Theme Customizer: Adding a New SettingTheme customizer 400
    By now, we've taken a look at what the Theme Customizer is, how it works, and the components that are unique to it. We've even discussed how options are serialized into the database so that we may retrieve them later when using our theme. To that end, it's time for us to begin doing our own work with the Theme Customizer. In this article, we're going to take a look at transports, how they work, and the difference in their two primary methods. Additionally, we're going to introduce our own control into one of WordPress' existing sections and see how it works with the various transport models.Read More…
  • Code
    Cheat Sheets
    The Complete Guide to Proper JavaScript Usage With WordPressJavascript 400
    I remember thinking "What the heck do we need JavaScript for, when we have Flash?" when I was fourteen. Although I still remember how I enjoyed coding stuff with ActionScript 2.0 back then, I saw how much one can achieve with JavaScript and fell in love with it. I'm not an expert on JavaScript (yet) but I can say I'm over and done with Flash for a long time. When it comes to WordPress, the biggest blogging platform and content management system worldwide, JavaScript is - of course - very useful for many things: content sliders, lightbox galleries, slick shopping carts, UI elements like tabs or accordions... you name it. But how exactly should we use JavaScript with WordPress? Returning or echoing a bunch of HTML script elements is one way to do it - and it's wrong. In this tutorial, we're going to see how to enqueue JavaScript files inside our pages and how to pass translatable data to the JavaScript code.Read More…