• Feed RSS

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

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