Fall Sale! Code FALL2024 takes 25% OFF our Pro Plugins & Books »
Web Dev + WordPress + Security

Stupid WordPress Tricks

[ WordPress ] One of the most popular articles here at Perishable Press is my January 2005 post, Stupid htaccess Tricks. In that article, I bring together an extensive collection of awesome copy-&-paste HTAccess code snippets. Four years later, people continue to tell me how much they enjoy and use the content as a bookmarked reference for many of their HTAccess needs. The article was even published in a book on Joomla! Security.

This is very inspiring to me, so I have decided to create a similar post for all of the useful WordPress code snippets, tips and tricks that I have collected while working on Digging into WordPress, the new book by co-author Chris Coyier and myself that really “digs in” to all of the awesome ways to get the most out of WordPress. While writing the DiW book, I collected hundreds of incredibly useful WordPress tips and tricks. After packing the book with as many of these techniques as possible, I decided to share the “best of the rest” here at Perishable Press.

If you are one of the millions of people who use WordPress, this article will help you improve the appearance, functionality, and performance of your WordPress-powered websites. Each of these “stupid WordPress tricks” is presented as clearly and succinctly as possible, including as many notes, instructions, and pointers as needed for successful implementation. Of course, keep in mind that we are only scratching the surface here. For a much more complete resource that is packed with tons of tasty techniques, you need to get Digging into WordPress.

So now, without further ado, here is my personal collection of easy-to-use, copy-&-paste WordPress tricks. Enjoy! :)

Table of Contents

  1. WordPress Shortcodes
  2. WordPress Permalinks Outside of the Loop
  3. Custom Message to Returning Visitors
  4. Recently Updated Posts and Pages
  5. Custom Content to Search Engine Visitors
  6. Last Modified Time and Date for Posts
  7. Display Total Number of Trackbacks and Pingbacks
  8. Display Recently Registered Users
  9. List all of Your Site’s Posts
  10. List WordPress User Information
  11. Display List of Scheduled Posts
  12. Display Private Posts to Logged-in Users
  13. Display Posts from Exactly One Year Ago
  14. Custom CSS Styles for Recent Posts
  15. New WordPress-2.7 Comments Loop
  16. Backwards-Compatible Comment Templates
  17. Disable WordPress Post Revisions
  18. Limit WordPress Post Revisions
  19. Remove WordPress Post Revisions from the Database
  20. Reduce Comment Spam by Blocking No-Referrer Requests
  21. Prevent Google Analytics from Tracking Admin Pages
  22. Meta Descriptions without a Plugin
  23. Differentiate Between Posts Depending on Presence of Excerpt
  24. Modify the wp_options Table via the WordPress Admin
  25. Alternate Comment Styles
  26. Automatically Remove Code Mistakes in Posts
  27. Automatically Disable Comments and Trackbacks in Old Posts
  28. Access Post Data Outside the Loop
  29. Display Posts for a Specified Time Period
  30. Unique Single Post Templates for Different Categories
  31. Display Performance Statistics for WordPress Pages
  32. Custom Post Thumbnails in Two Steps
  33. Highlight Author Comments
  34. Easy Random Posts
  35. Display Dates for Groups of Posts
  36. Display a Sticky Post in the Sidebar
  37. Display Latest Comments without a Plugin
  38. Display Most Commented Posts without a Plugin
  39. Change Permalinks from Date-Based to Post-Date Only
  40. Test for Sub-Pages
  41. Multiple Widgetizable Sidebars
  42. Remove Fancy Quotes from Comments
  43. Display a List of All Untagged Posts
  44. Easy Display of Custom Headers, Footers, and Sidebars
  45. A Better Way for Users to Logout
  46. Display a Custom Message on a Specific Date
  47. Display Three Columns of Posts
  48. Disable WordPress Search Functionality
  49. Display Posts with Specific Custom Fields
  50. How to Number Your Comments, Pingbacks, & Trackbacks in 2.7+
  51. How to Number Your Comments Using the Classic Loop
  52. Invite Readers to Comment via Feed
  53. Display the Total Number of Users for Your Blog
  54. Automatically Insert Content into Your WordPress Post Editor
  55. How to Prevent Duplicate Content
  56. Conditionally Display Full Posts or Excerpts
  57. Display Related Posts without a Plugin
  58. Drop-Dead Easy Styles for Author Comments
  59. Display Upcoming Scheduled Posts
  60. Display Automatic TinyURLs for Your Posts
  61. Implement a Site-Maintenance Page for Your Blog
  62. Display the First Image from Each of Your Posts
  63. Display Most Popular Posts without a Plugin
  64. Automatically Highlight Search Terms
  65. Automatically Disable Widgets
  66. Display All Images from Your Post Content
  67. Display Category List in Two Columns
  68. Show Ads or Other Content Only in the First Three Posts
  69. A Better Way to Display Recent Comments without a Plugin
  70. Selectively Disable Automatic Post Formatting
  71. Browser Detection via WordPress’ body_class Function
  72. Get Post or Page Contents as a PHP Variable
  73. Simple Example of How to Use WordPress Cron
  74. Add More Default Avatar Choices to the WordPress Admin
  75. Add a Private Page to Your Navigation Menu
  76. How to Add Additional Links to wp_list_pages

WordPress Shortcodes

Save time by replacing your most commonly typed words and phrases with WordPress shortcodes. For example, if you are frequently typing your blog’s URL, you could place the following code your theme’s functions.php file:

function shortURL() {
	return 'https://perishablepress.com/';
}
add_shortcode('myurl', 'shortURL');

Now whenever I write a post via “HTML-mode”, all I need to include my blog’s URL is type [myurl]. Works great in WordPress 2.5 or better.

Shortcodes with Attributes
To create a shortcode for links, we need to include the href attribute information as well as the anchor text for the link itself. We can do this by placing this function in your theme’s functions.php file:

function shortLink($atts, $content = null) {
	extract(shortcode_atts(array(
		"href" => 'http://' // default URL
	), $atts));
	return '<a href="'.$href.'">'.$content.'</a>';
}
add_shortcode('link', 'shortLink');

Then, when creating a post, emulate the following format to include any links you wish:

[link href="https://perishablepress.com/"]Perishable Press[/link]

..which will output the following code:

<a href="https://perishablepress.com/">Perishable Press</a>

When the href attribute is removed from the shortcode, the default URL will be used. You may specify the default URL in the third line of the funtion (see comment).

Source: Digging into WordPress

Display WordPress Permalinks Outside of the Loop

Normally, permalink display via the_permalink() requires the loop. To display permalinks outside of the loop, we may use either of the following methods:

<!-- external permalink via post ID -->
<a href="<?php echo get_permalink(33); ?>" >Permalink</a>

<!-- external permalink via global $post variable -->
<a href="<?php echo get_permalink($post->ID); ?>" >Permalink</a>

Display Custom Message to Returning Visitors

We can greet returning commentators with a custom message by extracting their information from the comment cookie left on their machine. Place the following code into the desired location in your theme and customize the message and markup to whatever you wish:

<?php if(isset($_COOKIE['comment_author_'.COOKIEHASH])) {
	$lastCommenter = $_COOKIE['comment_author_'.COOKIEHASH];

	echo "Welcome Back ". $lastCommenter ."!";

	} else {

	echo "Welcome, Guest!";
} ?>

Display Recently Updated Posts and Pages

Easily display a list of recently updated posts by placing the following code into the desired location in your theme:

<?php 

$today  = current_time('mysql', 1);
$number = 5; // number of posts

if($recentposts = $wpdb->get_results("SELECT ID, post_title FROM $wpdb->posts WHERE post_status = 'publish' AND post_modified_gmt < '$today' ORDER BY post_modified_gmt DESC LIMIT $number")):

?>

<h2><?php _e("Recently Updated"); ?></h2>
<ul>
<?php

foreach($recentposts as $post) {

	if($post->post_title == '') $post->post_title = sprintf(__('Post #%s'), $post->ID);
	echo '<li><a href="'.get_permalink($post->ID).'">'.the_title().'</a></li>';

} ?>
</ul>

<?php endif; ?>

Of course, customize the details as necessary and remember to set the number of posts via the $howMany variable.

Display Custom Content to Search Engine Visitors

Display custom content to your search-engine traffic by placing the following code into your theme’s functions.php file:

<?php function scratch99_fromasearchengine() {

	$ref = $_SERVER['HTTP_REFERER'];
	$SE  = array('/search?', 'images.google.', 'web.info.com', 'search.', 'del.icio.us/search', 'soso.com', '/search/', '.yahoo.');
	
	foreach($SE as $source) {
		if(strpos($ref, $source) !== false) return true;
	}
	return false;
} ?>

After checking and editing the $SE array with the search-engine referrer information of your choice, place this next chunk of code into the desired display location in your theme file(s):

<?php if(function_exists('scratch99_fromasearchengine')) {
	if (scratch99_fromasearchengine()) {

		// INSERT YOUR CODE HERE

	}
} ?>

Add whatever content or code you wish to the specified area and enjoy targeted delivery to search-engine visitors only.

Source: Stephen Cronin

Display Last Modified Time and Date for Posts

Display the “last-modified” time for your posts by placing this code anywhere within the loop:

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 ". ";
} ?>

Display Total Number of Trackbacks and Pingbacks

Display the trackback/pingback count for each of your posts by first placing this code into your theme’s functions.php file:

function comment_count() {
	global $wpdb;
	$count = "SELECT COUNT(*) FROM $wpdb->comments WHERE comment_type = 'pingback' OR comment_type = 'trackback'";
	echo $wpdb->get_var($count);
}

And then call the number for display anywhere in your theme by adding this code to the desired location:

<?php comment_count(); ?>

Alternately, in WordPress 2.7, you may display the total number of comments by inserting this code directly into your comments.php template:

<?php if(!empty($comments_by_type['comment'])) : 
	$count = count($comments_by_type['comment']);
	($count !== 1) ? $txt = "Comments" : $txt = "Comment"; 
?>
<h3><?php echo $count . " " . $txt; ?></h3>

Edit the markup as desired. Will display “” or “”, depending on the number of comments.

Source: WPengineer.com

Display Recently Registered Users

Quick and easy method for displaying a list of recently registered users. Place the following code directly into your theme, wherever you would like to display the list:

<ul>
	<?php $usernames = $wpdb->get_results("SELECT user_nicename, user_url FROM $wpdb->users ORDER BY ID DESC LIMIT 5");

		foreach ($usernames as $username) {
    			echo '<li><a href="'.$username->user_url.'">'.$username->user_nicename."</a></li>";
		}
	?>
</ul>

As-is, this code will spit out the five most recent registered users. This is easily changed to whatever number you wish by simply editing the number “5” in the first line.

List all of Your Site’s Posts

If the default wp_get_archives(type=postbypost&limit=) function doesn’t provide enough flexibility to meet your needs, here is another way to list all of your site’s posts:

<?php while(have_posts()) : the_post(); ?>
<ul>
	<?php $allposts = get_posts('numberposts=-1&offset=0'); foreach($allposts as $post) : ?>

	<li><?php the_time('d/m/y'); ?>: <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>

	<?php endforeach; ?>
</ul>
<?php endwhile; ?>

In place, that code will display a list of all of your blog’s posts. As a bonus, you may use any of the applicable parameters available to the get_posts() function to do just about anything you need with your posts list.

List WordPress User Information

Here is an easy way to display flexible lists of your blog’s registered users’ information. In this example, we will list the first and last name of each user registered in the database:

<ul>
<?php $szSort = "user_nicename";  
$aUsersID = $wpdb->get_col($wpdb->prepare("SELECT $wpdb->users.ID FROM $wpdb->users ORDER BY %s ASC", $szSort)); 
	foreach($aUsersID as $iUserID) :
		$user = get_userdata($iUserID);
		echo '<li>'.ucwords(strtolower($user->first_name.' '.$user->last_name)).'</li>'; 
	endforeach; 
?>
</ul>

The following variables may be used to display different types of user information and also to specify the sort order of the output list:

  • ID — User ID number
  • user_login — User Login name
  • user_nicename — nice version of login name
  • user_email — User Email Address
  • user_url — User Website URL
  • user_registered — User Registration date

To display any of these different types of user information, call it with $user->name_of_the_column anywhere within the function’s foreach() loop. To change the display order of the output, use any of the above as the value of the $szSort variable in the first line of the function. Note that strtolower and ucwords are used to ensure proper capitalization of the user names.

Display List of Scheduled Posts

Got scheduled posts? Cool. Here’s how to display them to your readers:

<ul>
<?php $my_query = new WP_Query('post_status=future&order=DESC&showposts=5');
if ($my_query->have_posts()) {
	while ($my_query->have_posts()) : $my_query->the_post(); $do_not_duplicate = $post->ID; ?>

        <li><?php the_title(); ?></li>

	<?php endwhile; } ?>
</ul>

Place that code in the desired location of your WordPress template and display a list of scheduled posts to your readers. To change the total number of displayed posts, edit the showposts=5 parameter to any number you wish. You may also use other parameters available to the WP_Query() function to further customize the output.

Display Private Posts to Logged-in Users

To display private posts to your logged-in users, you will need to add a custom field called private for each private post and give it a value of true. Then, replace your default WordPress loop with the following:

<?php if (have_posts()) : while (have_posts()) : the_post();

	$private = get_post_custom_values("private");
	if (isset($private[0]) && $private == "true") {
		if (is_user_logged_in()) {
			// Display private post to logged user
		}
	} else {
		// Display public post to everyone
	}

endwhile; endif; ?>

This custom loop will check each post for the presence of a custom-field value of true. For each post that has this value, the loop will then check to see if the user is logged into your site. If the user is in fact logged in, the loop will display the private post(s). Public posts will be displayed as usual and regardless of whether the user is logged in or not.

Source: Digging into WordPress

Display Posts from Exactly One Year Ago

Use this code to display posts that are exactly one year old:

<?php 
$current_day = date('j');
$last_year   = date('Y')-1; 
?>
<?php query_posts('day='.$current_day.'&year='.$last_year); 
	if (have_posts()): while (have_posts()) : the_post(); ?>

	<h1><?php the_title(); ?></h1>
	<?php the_excerpt(); ?>

<?php endwhile; endif; ?>

To display posts from different days or different years, edit the two variables in the beginning of the method.

Custom CSS Styles for Recent Posts

Use some custom CSS styles to highlight your recent posts. To do this, replace your existing loop with the following:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

	$currentdate = date('Y-m-d',mktime(0,0,0,date('m'),date('d'),date('Y')));
	$postdate = get_the_time('Y-m-d');
	if ($postdate == $currentdate) {

		echo '<div class="post new">';

	} else {

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

	} ?>

		<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
	</div>

<?php endwhile; endif; ?>

This new loop will check the date of each post and include a CSS class of new to any post published within the previous 24-hour time period. Once the new post class is included, you may style it with some custom CSS such as the following:

.post{
	/* styles for all posts */
	}
.post.new {
	/* styles for new posts */
	}

New WordPress-2.7 Comments Loop

Due to the changes made to comment-related functions in WordPress 2.7, you will need to upgrade your comments template in order accomodate for the new functionality. The major changes are the new wp_list_comments() function and the next/previous_comments_link() functions. Here is an example comments.php loop to get you started:

<?php if (have_comments()) : ?>

	<h4><?php comments_number('No Comments', 'One Comment', '% Comments' );?></h4>
	<ul class="commentlist">
		<?php wp_list_comments(); ?>
	</ul>
	<div class="navigation">
		<div class="alignleft"><?php previous_comments_link(); ?></div>
		<div class="alignright"><?php next_comments_link(); ?></div>
	</div>

<?php else : // if there are no comments so far ?>

	<?php if ('open' == $post->comment_status) : ?>

		<p>Comments are open, but there are no comments.</p>

	<?php else : ?>

		<p>Comments are closed, and there are no comments.</p>

	<?php endif; ?>

<?php endif; ?>

As you can see, we are now using the wp_list_comments() function as the method by which our individual comments are displayed. This function wraps each comment with a set of <li> elements, but this may be changed via customized parameters. We are also using the next/previous_comments_link() functions to accommodate the new built-in paged comments feature.

Source: Digging into WordPress

Backwards-Compatible Comment Templates

The easiest way to accommodate for both old (pre-2.7) and new (2.7+) WordPress comment loops is to create two different versions of the comments template and then use some conditional logic to process the correct file. Place the 2.7-compatible code from the previous section into your default comments.php file, and then place your existing (pre-2.7) comments code into a file called legacy-comments.php. Once you have both of these files setup and included among your theme files, place the following function in your theme’s functions.php file:

<?php add_filter('comments_template', 'legacy_comments');

function legacy_comments($file) {
	if(!function_exists('wp_list_comments')) : // WP 2.7-only check
		$file = TEMPLATEPATH.'/legacy-comments.php';
	endif;
	return $file;
} ?>

This code will then check for the presence of the new wp_list_comments() function. If it exists, then the version of WordPress is at least 2.7, and the default comments.php file will be used. If the new function doesn’t exist, we have a dinosaur on our hands and so the legacy comments file will be used instead.

Disable WordPress Post Revisions

One of the new features rolled out in WordPress 2.6 involved post revisions. Revisions are a way for users to keep a working collection of each different version of a post and then revert back to it in the future if necessary. Some people think this is the greatest thing since lightsabers, others (such as myself) find it to be a royal pain in the database. It convolutes the Admin area, gobbles up disk space, and usually doesn’t work as intended. Fortunately, we can disable this amazing new “feature” (which should NOT have been included in the core) by adding the following line to the wp-config.php file:

/* disable post-revisioning nonsense */ 
define('WP_POST_REVISIONS', FALSE);

Just place that line above the “Happy blogging” comment and say goodbye to needless revisioning bloat.

Source: Digging into WordPress

Limit WordPress Post Revisions

If you like the idea of WordPress-2.6’s new post-revisioning feature, but don’t want thousands of extra records bloating up your database, here is an easy way to limit the total number of revisions that WordPress is allowed to keep. This code will instruct WordPress to keep only the most recent “x” number of revisions:

/* limit number of post revisions */ 
define('WP_POST_REVISIONS', 3);

Place that line above the “Happy blogging” comment in the wp-config.php file and enjoy conserved disk space and less Admin clutter. Change the number 3 to any number you wish. Works a treat.

Source: Digging into WordPress

Remove WordPress Post Revisions from the Database

In line with the previous two sections, here we will remove all existing post revisions from the WordPress database. This is useful if you have disabled the post-revisioning feature or perhaps even reduced the total number of allowed revisions. The easiest way to do this is to run the following SQL command via your favorite database interface (such as my personal favorite, phpMyAdmin):

DELETE a,b,c FROM wp_posts a LEFT JOIN wp_term_relationships b ON (a.ID = b.object_id) LEFT JOIN wp_postmeta c ON (a.ID = c.post_id) WHERE a.post_type = 'revision';

Note that if you have changed the default WordPress database table prefix to something other than wp_, you will want to edit the command to reflect the correct prefix information. This information is available in your site’s wp-config.php file. Also note that you should backup your database before casting any SQL spells on it.

Upon successful execution of the above command, all data associated with post revisions will be removed the database. This includes the post revisions themselves and all the meta data associated with each revision.

Credit: Andrei Neculau

Reduce Comment Spam by Blocking No-Referrer Requests

As explained in my article, denying access to no-referrer requests, you can greatly reduce the number of spam comments by eliminating all direct requests for your blog’s comments-post.php file. This will block automated spam scripts from bypassing your comments form by hitting the comment processing script directly. Here are two ways to block no-referrer comment requests, one uses HTAccess and the other uses PHP. Here is the HTAccess method:

RewriteEngine On
RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{REQUEST_URI} .wp-comments-post.php
RewriteCond %{HTTP_REFERER} !domain.tld [OR]
RewriteCond %{HTTP_USER_AGENT} ^$
RewriteRule (.*) http://%{REMOTE_ADDR}/$ [R=301,L]

Place that code in your site’s root HTAccess file and edit the domain.tld to match your own domain. Once in place, this code will redirect any request for your blog’s comments-post.php file that didn’t originate from your site back to the URL from whence it came.

This may also be accomplished via PHP. Place the following function in your theme’s functions.php file:

function check_referrer() {
	if (!isset($_SERVER['HTTP_REFERER']) || $_SERVER['HTTP_REFERER'] == '') {
		wp_die(__('Please do not access this file directly.'));
	}
}
add_action('check_comment_flood', 'check_referrer');

Source: Perishable Press

Prevent Google Analytics from Tracking Admin Pages

This handy snippet will prevent Google Analytics from tracking your Admin pages or anything else that you wish. Replace your default Google Analytics code with the following:

<?php if (!current_user_can('level_10')) { ?>

	/* Google Analytics Code */

<?php } ?>

This code will then include your Google Analytics code only on non-Admin pages. This in turn will prevent Google Analytics from gathering statistics about your Admin pages. Note that the basic functionality of this method is great for restricting just about anything — scripts, markup, content — to logged-in administrators.

Meta Descriptions without a Plugin

We don’t need no stinkin’ plugin for custom meta descriptions. All you need is a custom field named metadescription with the desired meta description for each post. Once you have that going, include the following function to your theme’s header.php file (within the <head> section:

<meta name="description" content="
<?php if ((is_home()) || (is_front_page())) {
	echo ('Your main description goes here');
} elseif(is_category()) {
	echo category_description();
} elseif(is_tag()) {
	echo 'Tag archive page for this blog - ' . single_tag_title();
} elseif(is_month()) {
	echo 'Archive page for this blog - ' . the_time('F, Y');
} else {
	echo get_post_meta($post->ID, 'metadescription', true);
} ?>" />

This function enables you to customize the descriptions for various types of pages, such as the home page, category pages, tag archives, and so on. For single post-view pages, this function will display the value of the metadescription custom field.

Differentiate Between Posts Depending on Presence of Excerpt

Here is a quick conditional snippet that displays different content depending on the presence of an excerpt:

<?php if(!empty($post->post_excerpt)) {

	// this post has an excerpt, so display it:
	the_excerpt();

} else {

	// this post has no excerpt, so display something else instead:
	the_content();

} ?>

Placed inside the loop, this code will check each post for an excerpt. If one is found, the excerpt is displayed; otherwise, the code specified in the else condition is displayed.

Modify the wp_options Table via the WordPress Admin

As you probably know, the wp_options table stores a great deal of useful information, including everything from custom-field values, plugin settings, blog information, and much more. If any table in the WordPress database needs its own friendly user-interface, this would be it.

Normally, you would access the wp_options table using a database interface such as phpMyAdmin. This certainly works, but there is a much easier way to work with the options table, especially if you are already logged into WordPress. Once logged in to the Admin area, navigate to the following URL:

http://domain.tld/wp-admin/options.php

This will open a “secret” Admin page that provides editable options fields for every record in the wp_options table. Bookmark this page, and save yourself a trip to phpMyAdmin!

Source: Digging into WordPress

Alternate Comment Styles

Alternating comments for old versions of WordPress (pre-2.7)
This is one of the oldest tricks in the book, but it is still a favorite. Alternating comment styles is a great way to enhance usability and add some stylistic flair to your comments display. The trick is to add an alternating set of classes — odd or even — to the containing element of each comment. While there are many ways to do this, here is one of the easiest. Open your comments.php and modify the comments loop as follows:

<ul>
	<?php $i = 0; ?>
	<?php foreach ($comments as $comment) : ?>
	<?php $i++; ?>

	<li id="comment-<?php comment_ID(); ?>" <?php if($i&1) { echo 'class="odd"'; } else { echo 'class="even"'; } ?>>
		<?php comment_text(); ?>
	</li>
	<php endforeach; ?>
</ul>

With that code in place, your comments will now have alternating CSS classes with which to apply custom styles to your oddly and evenly numbered comments:

.odd {
	background: white;
	color: black;
	}
.even {
	background: black;
	color: white;
	}

Alternating comments for old versions of WordPress (pre-2.7)
In WordPress 2.7 and better, comments automagically include odd and even classes for oddly and evenly numbered comments, respectively. This makes it a snap to throw down your own custom CSS styles for each of these classes.

Automatically Remove Code Mistakes in Posts

Here is a handy trick that will automatically remove basic mistakes in XHTML markup, such as empty paragraphs, inline font styles, and more. Place this function in your functions.php file:

function clean_bad_content($bPrint = false) {
	global $post;
	$szPostContent  = $post->post_content;
	$szRemoveFilter = array("~<p[^>]*>\s?</p>~", "~<a[^>]*>\s?</a>~", "~<font[^>]*>~", "~<\/font>~", "~style\=\"[^\"]*\"~", "~<span[^>]*>\s?</span>~");
	$szPostContent  = preg_replace($szRemoveFilter, '', $szPostContent);
	$szPostContent  = apply_filters('the_content', $szPostContent);
	if ($bPrint == false) return $szPostContent; 
	else echo $szPostContent;
}

Once in place, use the following function call to display your “cleaned” content in the loop:

<?php if (function_exists('clean_bad_content')) clean_bad_content(true); ?>

Note that the clean_bad_content() accepts a boolean argument (true or false) specifying whether or not to print the function output.

Automatically Disable Comments and Trackbacks in Old Posts

Here is yet another method for auto-disabling comments and trackbacks on old posts. This function automatically closes comments and trackbacks after the specified number of days. Add the following to your functions.php file:

<?php function autoclose_comments() {
	global $wpdb, $tableposts;

	if (!isset($tableposts))
		$tableposts = $wpdb->posts;

		$age = '21 DAY';
 
		$date = $wpdb->get_var("SELECT DATE_ADD(DATE_SUB(CURDATE(), INTERVAL $age), INTERVAL 1 DAY)");
		$wpdb->query("UPDATE $tableposts SET comment_status = 'closed' WHERE comment_status = 'open' AND post_status = 'publish' AND post_date < '$date'");
}

function autoclose_trackback() {
	global $wpdb, $tableposts;

	if (!isset($tableposts))
		$tableposts = $wpdb->posts;

		$age = '21 DAY';
 
		$date = $wpdb->get_var("SELECT DATE_ADD(DATE_SUB(CURDATE(), INTERVAL $age), INTERVAL 1 DAY)");
 		$wpdb->query("UPDATE $tableposts SET ping_status = 'closed' WHERE comment_status = 'open' AND post_status = 'publish' AND post_date < '$date'");
}

add_action('publish_post',   'autoclose_trackback', 7);
add_action('edit_post',      'autoclose_trackback', 7);
add_action('delete_post',    'autoclose_trackback', 7);
add_action('comment_post',   'autoclose_trackback', 7);
add_action('trackback_post', 'autoclose_trackback', 7);
add_action('pingback_post',  'autoclose_trackback', 7);
add_action('edit_comment',   'autoclose_trackback', 7);
add_action('delete_comment', 'autoclose_trackback', 7);
add_action('template_save',  'autoclose_trackback', 7);
 
add_action('publish_post',   'autoclose_comments', 7);
add_action('edit_post',      'autoclose_comments', 7);
add_action('delete_post',    'autoclose_comments', 7);
add_action('comment_post',   'autoclose_comments', 7);
add_action('trackback_post', 'autoclose_comments', 7);
add_action('pingback_post',  'autoclose_comments', 7);
add_action('edit_comment',   'autoclose_comments', 7);
add_action('delete_comment', 'autoclose_comments', 7);
add_action('template_save',  'autoclose_comments', 7);
?>

Once in place, you may change the number of days allowed for comments and trackbacks to stay open by editing the two instances of the $age variable to whatever you wish. No other editing or code is required for this function to operate effectively. The function is executed automatically upon various posting actions. Note that this function is included in newer versions of WordPress (2.7 or better), and is therefore only required for older versions.

Source: WP Engineer
Plugin: Autoclose

Access Post Data Outside the Loop

The easiest way to access and display post data outside of the loop is to use the built-in WordPress core function get_post(); however, for more control over the process, check out this nifty little function from WP Recipes:

function get_post_data($postId) {
	global $wpdb;
	return $wpdb->get_row("SELECT * FROM $wpdb->posts WHERE ID=$postId");
}

Place this function in your functions.php and then add this code to the desired location outside of the loop:

<?php $data = get_post_data(77);
	echo $data->post_date;     // post date
	echo $data->post_title;    // post title
	echo $data->post_content;  // post content
	echo $data->comment_count; // comments number
?>

For the argument of the function, specify the post ID for which you would like to display data. The function will return an array containing all of the available fields for the specified post (post_title, date, content, author_id, post_id, etc).

Display Posts for a Specified Time Period

Here is an easy way to create posts that will only be displayed for the duration of a specified time period. Replace your current loop with the following:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
	$expirationtime = get_post_custom_values('expiration');
	if (is_array($expirationtime)) {
		$expirestring = implode($expirationtime);
	}
	$secondsbetween = strtotime($expirestring)-time();
	if ($secondsbetween > 0) { ?>

		<h1><?php the_title(); ?></h1>
		<?php the_excerpt(); ?>

<?php } endwhile; endif; ?>

And then add a custom field named expiration to any post that needs an expiration date. For the value of the expiration key, specify the date/time in the following format: mm/dd/yyyy 00:00:00. Each post that contains such a custom field will expire after the specified date and time and will no longer appear in the loop.

Unique Single Post Templates for Different Categories

Here is an easy way to display custom post styles depending on the post’s category. With the following code, each single-view post will be displayed according to a template that is specific to the post’s category:

<?php $post = $wp_query->post;
if (in_category('1')) {
	include(TEMPLATEPATH.'/single-01.php');
} elseif (in_category('2')) {
	include(TEMPLATEPATH.'/single-02.php');
} else {
	include(TEMPLATEPATH.'/single-default.php');
} ?>

This code should be placed in your theme’s single.php file. As written, this code will display posts from the first category with the single template, single-01.php; also, posts from the second category will be displayed with a single template named single-02.php; finally, all other posts will be displayed via the default single template, single-default.php. Of course, you will want to customize the category IDs according to your own needs, and also you will want to create the customized single files as they are called. That’s all there is to it.

Having said that, here is an alternate version of the custom-post-template script:

<?php add_filter('single_template', create_function('$t', 'foreach((array) get_the_category() as $cat) { if (file_exists(TEMPLATEPATH . "/single-{$cat->term_id}.php")) return TEMPLATEPATH . "/single-{$cat->term_id}.php"; } return $t;')); ?>

Placed in your theme’s functions.php file, this alternate script checks all categories for the presence of a custom single template. Any category with a custom single-post template will then have its posts displayed with that template. If a post’s category does not feature a custom template, the default single.php template will be used. Note that this code will use the template for the first listed category of each post. Even so, you should only create custom post templates for categories that will always be mutually exclusive. That is, make sure that your posts aren’t in more than one custom-templated category.

Source: Austin Matzko

Display Performance Statistics for WordPress Pages

Everyone is familair with the following information:

<!-- 33 queries in 0.333 seconds -->

These statistics are usually seen in the footer area of individual pages and serve as a general indicator of performance. The “queries” refer to the number of times WordPress requested information from the database, while the number of seconds indicates the amount of time required for Apache to generate the page. This information is generated by including the following code in your footer template file (or wherever you would like):

<!-- <?php echo get_num_queries(); ?> queries in <?php timer_stop(3); ?> seconds -->

Or, if you don’t like the idea of sharing this information with the entire world, you can limit its display to logged-in administrators only:

<?php if (current_user_can('level_10')) {

	echo '<!-- ' . get_num_queries() . ' queries in ' . timer_stop(3) . ' seconds -->';

} ?>

Easy breezy beautiful!

Source: Digging into WordPress

Custom Post Thumbnails in Two Steps

Alright, kids. Time for the ‘ol three-step custom-field tutorial. This time we’re going to implement post thumbnails. You know, representative images for each of your posts that may be displayed anywhere you wish, including outside of the flow of post content, and even outside of the loop. This is a great trick for advanced page layouts. Ready? Sharpen your keystrokes!

Step 1:
Open your write panel and create a key called “thumbnail”. Then, for the value of the “thumbnail” key, enter the URL of the thumbnail image for that particular post. Write the post and then publish it as normal. Wash, rinse, repeat to get a nice collection of posts with thumbnails. Or, go back to exisiting posts and add a thumbnail as we have just described.

Step 2:
Open your theme template file containing the loop and add the following code to the location where you would like the post thumbnail images to appear:

<?php $thumbnail = get_post_meta($post->ID, 'image', true); if ($thumbnail) { ?>

<img src="<?php echo $thumbnail; ?>" alt="" width="100" height="100" />

<?php } ?>

That’s it! Don’t forget to edit the width and height attributes of the <img> element to account for the proper image size.

Source: Perishable Press

Highlight Author Comments

Make your author comments look fabulous darling! Newer versions of WordPress come equipped with a specific author class that may be targeted with the CSS of your choice. For older versions of WordPress, however, you will need to add the custom class attribute with a little PHP magic.

First, open your theme’s comments.php template and add the following code snippet in the (X)HTML element that contains the comment information:

<div<?php if ($comment->comment_author_email == "email@domain.tld") echo ' class="author"'; ?> id="comment-<?php comment_ID(); ?>">
.
.
.
</div>

After changing the email address to that of your own (i.e., the one used for your WP Admin user profile), style it up with a little CSS:

.author {
	background: red !important;
	color: yellow   !important;
	}

You probably don’t want your author comments to appear with yellow text on a red background, but you get the idea. Anything is possible.

For blogs with multiple authors, you can style each of their comments differently as well by using something like this:

<div<?php if ($comment->comment_author_email == "email-01@domain.tld") echo ' class="author-01"'; elseif ($comment->comment_author_email == "email-02@domain.tld") echo ' class="author-02"'; elseif ($comment->comment_author_email == "email-03@domain.tld") echo ' class="author-03"'; ?> id="comment-<?php comment_ID(); ?>">
.
.
.
</div>

Replace each of the email addresses with those of the various authors. Style to taste.

Easy Random Posts

Newer versions of WordPress enable easy randomizing of posts by using the (relatively) new orderby=rand parameter in any query_posts loop:

<?php query_posts('orderby=rand"); ?>

But for older versions of WordPress, this randomizing functionality must be added manually. Here is a quick and painless plugin that will enable you to randomize post queries in older versions:

<?php
/*

Plugin Name: Random Posts Query

*/

function query_random_posts($query) {
	return query_posts($query . '&random=true');
}
class RandomPosts {
	function orderby($orderby) {
		if (get_query_var('random') == 'true')
			return "RAND()";
		else
			return $orderby;
	}
	function register_query_var($vars) {
		$vars[] = 'random';
		return $vars;
	}
}
add_filter( 'posts_orderby', array('RandomPosts', 'orderby') );
add_filter( 'query_vars', array('RandomPosts', 'register_query_var') );
?>

Once activated, invoke the randomness by adding the random=true parameter in your query_posts loop:

<?php query_posts('cat=11&showposts=11&random=true'); ?>

Here, we are specifying cat=11 for the category and showposts=11 for the number of posts to display. There are many other parameters available as well, so knock yourself out.

Credit: rembem

Display Dates for Groups of Posts

In order to display the date that a post was published, you have two options:

  • <?php the_time(); ?> — displays the date for each and every post
  • <?php the_date(); ?> — displays the date only once for each group of posts published on a certain day

So, if you want to list the post date next to each post, use the the_time(). If, on the other hand, you have multiple posts on any given day, use the_date() to list the post date only once for each days’ posts. Something like this:

// the_time();

	Jan 01, 2009 - Post #1
	Jan 01, 2009 - Post #2
	Jan 01, 2009 - Post #3

	Jan 02, 2009 - Post #4
	Jan 02, 2009 - Post #5
	Jan 02, 2009 - Post #6

	Jan 03, 2009 - Post #7
	Jan 03, 2009 - Post #8
	Jan 03, 2009 - Post #9

// the_date();

	Jan 01, 2009
		Post #1
		Post #2
		Post #3

	Jan 02, 2009
		Post #4
		Post #5
		Post #6

	Jan 03, 2009
		Post #7
		Post #8
		Post #9

See the difference? Good, because I’m not going to explain the concept any further. Instead, I will move on by showing you how to use either template tag in your loop. This really doesn’t need explaining either, but for the sake of completeness, here it is. First, the_time() tag:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

	<h1><?php the_title(); ?></h1>
	<p><?php the_time(); ?><p>
	<?php the_content(); ?>

<?php endwhile; ?>
<?php else : ?>
<?php endif; ?>

This loop will output the post title, date, and content for every post. Alternately, here is how to use the_date tag:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

	<?php the_date('','<p>','</p><hr />'); ?>
	<h1><?php the_title(); ?></h1>
	<?php the_content(); ?>
 
<?php endwhile; ?>
<?php else : ?>
<?php endif; ?>

This loop will output the post title and content for every post, and also output the date for each group of posts published on any given day, as explained above. Notice we are adding the paragraph elements for the post date based on whether or not the date is actually output. If it is, then the date will be wrapped in <p> elements; if it’s not, no <p> elements will be output, thereby preventing repetitive sets of empty paragraph elements. Make sense? Good. Here are the available parameters for the nifty the_date() template tag:

<?php the_date('date format', 'before the date', 'after the date'); ?>

Display a Sticky Post in the Sidebar

Here is a juicy little nugget that displays a “sticky” post in the sidebar of your theme:

<?php 
// initialize new query of one post from category 11
$my_query = new WP_Query('cat=11&showposts=1');

// loop through the database to find related information
while ($my_query->have_posts()) : $my_query->the_post();

// set expiration time of two days
$goAwayDate = time() - (60 * 60 * 24 * 2);

// get date of sticky post
$postDate = get_the_time('U');

// if post is too old, do nothing
if ($postDate < $goAwayDate) {

// else show the post
} else { ?>

	<h1><?php the_title(); ?></h1>
	<?php the_excerpt(); ?>

<?php } endwhile; ?>

This method employs a second loop to display the sticky post, so it may be placed just about anywhere in your theme’s template files. You can also change the number of days that the post will remain sticky by editing the expiration variable with a number other than "2". For example, to set a duration period of seven days, you would use this:

$goAwayDate = time() - (60 * 60 * 24 * 7);

Credit: The Closet Entrepreneur

Display Latest Comments without a Plugin

Good rule of thumb when working with WordPress: don’t use a plugin if you can acheive the same functionality without one. Case in point: displaying latest comments on your blog. Sure, you could always install a plugin to do it for you, but you really don’t need to. In fact, it’s actually easier to display recent comments without a plugin. SImply add the following code to the desired location within your theme’s template files:

<?php global $wpdb;

$sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID, 
comment_post_ID, comment_author, comment_date_gmt, comment_approved, 
comment_type,comment_author_url, 
SUBSTRING(comment_content,1,50) // NUMBER OF CHARACTERS
AS com_excerpt FROM $wpdb->comments 
LEFT OUTER JOIN $wpdb->posts 
ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) 
WHERE comment_approved = '1' 
AND comment_type = '' 
AND post_password = '' 
ORDER BY comment_date_gmt 
DESC LIMIT 5"; // NUMBER OF COMMENTS

$comments = $wpdb->get_results($sql);
$output   = $pre_HTML;
$output  .= "\n<ul>";

foreach ($comments as $comment) {
	$output .= "\n<li>"."<a href=\"" . get_permalink($comment->ID) . 
	"#comment-" . $comment->comment_ID . "\" title=\"on " . 
	$comment->post_title . "\">" .strip_tags($comment->comment_author) 
	.":<br/><div>" . strip_tags($comment->com_excerpt) 
	."</div></a></li>";
}
$output .= "\n</ul>";
$output .= $post_HTML;

echo $output;
?>

This code will display the 5 most recent comments in the following (X)HTML output format:

<ul>
	<li>
		<a href="http://domain.tld/post#comment-01" title="on Post Title">Comment Author:<br />
		<div>This is the first 50 characters of the first most recent comment</div></a>
	</li>
	<li>
		<a href="http://domain.tld/post#comment-01" title="on Post Title">Comment Author:<br />
		<div>This is the first 50 characters of the first most recent comment</div></a>
	</li>
	<li>
		<a href="http://domain.tld/post#comment-01" title="on Post Title">Comment Author:<br />
		<div>This is the first 50 characters of the first most recent comment</div></a>
	</li>
	<li>
		<a href="http://domain.tld/post#comment-01" title="on Post Title">Comment Author:<br />
		<div>This is the first 50 characters of the first most recent comment</div></a>
	</li>
	<li>
		<a href="http://domain.tld/post#comment-01" title="on Post Title">Comment Author:<br />
		<div>This is the first 50 characters of the first most recent comment</div></a>
	</li>
</ul>

By editing the commented lines in the PHP script, you may specify alternate number of comments and characters.

Display Most Commented Posts without a Plugin

Here is another trick that will enable you avoid yet another needless plugin. This code results in the display of your most-commented posts in list format:

<ul>
<?php 
$result = $wpdb->get_results("SELECT comment_count, ID, post_title FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 , 10"); // NUMBER OF POSTS
foreach ($result as $topten) {
	$postid = $topten->ID;
	$title = $topten->post_title;
	$commentcount = $topten->comment_count;
	if ($commentcount != 0) {
?>

<li><a href="<?php echo get_permalink($postid); ?>"><?php echo $title ?></a></li>

<?php } } ?>
</ul>

This code may be modified to display any number of posts by changing the LIMIT from 10 to whatever you wish. You may also change the display order from DESC (descending order) to ASC (ascending order).

Once in place, this code will display a list of the 10 most-commented posts in the following (X)HTML output format:

<ul>
<li><a href="http://domain.tld/post-01/">Post Title 01</a></li>
<li><a href="http://domain.tld/post-02/">Post Title 02</a></li>
<li><a href="http://domain.tld/post-03/">Post Title 03</a></li>
.
.
.
</ul>

Change Permalinks from Date-Based to Post-Date Only

Here is an HTAccess method for switching your permalinks from the lengthy date-based format (i.e., http://domain.tld/2009/03/03/post-name/) to the concise post-name format (i.e., http://domain.tld/post-name/).

To do so, first login to the WordPress Admin and switch your permalink structure from this:

/%year%/%monthnum%/%day%/%postname%/

..to this:

/%postname%/

This change will ensure that all future posts are located at the new post-name-only URL, but we still need to redirect all requests for existing posts via the old date-based URL format. This is easily accomplished with a single directive in your site’s root HTAccess file:

RedirectMatch 301 /([0-9]+)/([0-9]+)/([0-9]+)/(.*)$ http://domain.tld/$4

And that’s all there is to it! Remember to test vigorously to convince yourself that everything is working properly.

Source: Perishable Press

Test for Sub-Pages

Until WordPress includes an is_subpage() function, here is a manual method of testing for sub-pages:

<?php global $post;

if ( is_page() && $post->post_parent ) {

    // subpage content goes here

} else {

    // non-subpage content goes here

} ?>

Further, here are some other ways to use this method to test for different combinations of pages and sub-pages:

<?php if (is_page('about') || $post->post_parent == '1') {

	$banner = 'business.png';

} elseif (is_page('archives') || $post->post_parent == '2') {	

	$banner = 'pleasure.png';

} elseif (is_page('contact') || $post->post_parent == '3') {

	$banner = 'personal.png';

} else { 

	$banner = 'default.png';

} ?>

Note that the numbers 1, 2, and 3 represent the IDs of the target parent pages.

Multiple Widgetizable Sidebars

Instead of using multiple if statements to include multiple widgetizable areas, WPEngineer shows us how to do it a better way:

<?php // multiple widgetizable sidebars
if (function_exists('register_sidebar')) {
	$sidebars = array('Home Sidebar', 'Post Sidebar', 'Page Sidebar');
	foreach($sidebars as $name) {
		register_sidebar(array('name'=> $name,
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
			'after_widget' => '</div>',
			'before_title' => '<h3 class="widgetTitle">',
			'after_title' => '</h3>',
		));
	}
}
?>

Source: wpengineer

Remove Fancy Quotes from Comments

Prevent invalid markup and sloppy code by disabling WordPress’ automatic generation of “fancy” or “curly” quotes where they fail the most: your comments area.

Only one simple line of code is required, placed into your theme’s functions.php file:

remove_filter('comment_text', 'wptexturize');

Display a List of All Untagged Posts

Here is an easy way to display a list of all untagged posts. All that’s required is a custom loop and a quick check of the get_the_tags variable. Here is the code to make it work:

<?php query_posts('orderby=title&order=asc&showposts=-1'); ?>
<?php if (have_posts()) : ?> 
	<ul>
	<?php while (have_posts()) : the_post(); ?>
	<?php $tag = get_the_tags(); if (!$tag) { ?>

		<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
		<?php edit_post_link('Edit', ' ',''); ?></li>

	<?php } ?>
	<?php endwhile; ?>
	</ul>
<?php endif; ?>

Place that snippet into the theme file of your choice and navigate to that page in a browser to see a permlink-linked list of all posts that have not yet been tagged. Even better, next to each post title will be a an easy-access “Edit” link that will make it easy to quickly edit each of your untagged posts and add some tags, if necessary. Nothing on this planet could be easier. Almost.

Easy Display of Custom Headers, Footers, and Sidebars

WordPress 2.7 includes new functionality that makes it super-easy to include custom headers, footers, and sidebars into your theme. Normally, you include the default files with the following tags:

<?php get_header(); ?>

<?php get_sidebar(); ?>

<?php get_footer(); ?>

These will include the files named header.php, sidebar.php, and footer.php, respectively.

Now, to include alternate versions of these files, simply include the name of the file as a parameter in its associated tag. Here is an example that should illustrate the idea:

<?php get_header('custom-header'); ?>

<?php get_sidebar('custom-sidebar'); ?>

<?php get_footer('custom-footer'); ?>

These will include the files named custom-header.php, custom-sidebar.php, and custom-footer.php, respectively.

We can now use this new functionality to get fine-grained with includes. For example, if we wanted to display a custom footer for the “Bananaz” category, we could use the following code:

<?php if is_category('Bananaz') {
	get_footer('Bananaz');
} else {
	get_footer();
} ?>

Source: WordPress Codex

A Better Way for Users to Logout

The old way of displaying a “Logout” link for your users looks like this:

<a href="<?php echo get_option('siteurl'); ?>/wp-login.php?action=logout">Logout</a>

Now, since WordPress 2.7, we can simplify this hodgepodge with a sleeker, cleaner, built-in template tag:

<a href="<?php echo wp_logout_url(); ?>">Logout</a>

Sweetness.

Display a Custom Message on a Specific Date

Using a snippet of PHP, we can display a custom message (or any code, markup, or content) on a specific date:

<?php
if ((date('m') == 4) && (date('d') == 9)) { ?>

	<p>Today is <a href="http://naked.dustindiaz.com/">CSS Naked Day</a>!</p>

<?php } ?>

You could even use this technique to join in on CSS Naked Day by removing your stylesheet on that day. Simply wrap your CSS <link> as follows:

<?php // strip for CSS Naked Day
if ((date('m') !== 4) && (date('d') !== 9)) { ?>

<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" />

<?php } ?>

The possibilities are endless!

Display Three Columns of Posts

Displaying content in multiple columns is a much sought-after WordPress technique. There are some good tutorials around explaining various ways of doing the job, but this one is perhaps the easiest.

To display your posts in three columns, begin by segmenting your post with some HTML comments:

Lorem ipsum blah blah. This content appears before the three columns.

<!--column-->

This content will appear in the first column.

<!--column-->

This content will appear in the second column.

<!--column-->

This content will appear in the third column.

The next step is to create columns based on the markup comments. Open your theme file and include the following code within the loop:

<?php // multiple columns

$page_columns = explode("<--column-->", $post->post_content);

echo $page_columns[0]; // before columns

echo '<div class="first column">'.$page_columns[1].'</div>'; // first column

echo '<div class="second column">'.$page_columns[2].'</div>'; // second column

echo '<div class="third column">'.$page_columns[3].'</div>'; // third column

?>

That’s essentially all there is to it. To get the columns to actually look like columns, add something similar to the following in your CSS file:

/* column structure */
.column {
	margin-right: 10px;
	float: left;
	width: 33%;
	}
/* column styles */
column.first, column.second, column.third {}

The cool thing about this method is that you have full control over the layout of each particular post. Each column may contain as much or as little content as desired, and adding or removing columns is straightforward. Even better is that you can easily remove the column functionality and display your content in a single column by simply removing the custom code from the loop. The post markup consists of HTML comments, so they will be ignored if not acted upon from within the loop.

Source: Enhanced version of krimsly’s technique (via the WP Codex)

Disable WordPress Search Functionality

Disabling the WordPress search functionality is as simple as adding the following code to your functions.php file:

function fb_filter_query($query, $error = true) {
 
	if (is_search()) {
		$query->is_search = false;
		$query->query_vars[s] = false;
		$query->query[s] = false;
 
		// to error
		if ($error == true)
			$query->is_404 = true;
	}
}
if (!is_admin()) {
	add_action('parse_query', 'fb_filter_query');
	add_filter('get_search_form', create_function('$a', "return null;"));
}

In place, this code will disable the search form for your theme while leaving search functionality intact for the Admin area. As is, the $error variable is set to TRUE, which causes the function to display the theme’s error page. Setting this variable to FALSE will prevent the error message and keep the user on the same page.

Source: WPengineer

Display Posts with Specific Custom Fields

Displaying posts that are associated with a certain custom field is as easy as adding an if condition to your loop. Here is an example that checks for the presence of a custom field called “name-of-custom-field”. If such a custom field is associated with the post, the entire post is displayed; otherwise, only the excerpt is displayed.

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php $custom_field = get_post_custom_values("name-of-custom-field"); ?>

	<?php if (isset($custom_field[0])) { ?>

		<h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
		<?php the_content(); ?>

	<?php } else { ?>

		<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
		<?php the_excerpt(); ?>

	<?php } ?>

<?php endwhile; endif; ?>

To get more specific and display only posts associated with a custom-field that is set to a certain value, we simply add an additional parameter to the if condition:

<?php if ((isset($custom_field[0])) && ($custom_field[0] == "name-of-value")) { ?>

Using that line of code, we modify our previous loop as follows:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php $custom_field = get_post_custom_values("name-of-custom-field"); ?>

	<?php if ((isset($custom_field[0])) && ($custom_field[0] == "name-of-value")) { ?>

		<h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
		<?php the_content(); ?>

	<?php } else { ?>

		<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
		<?php the_excerpt(); ?>

	<?php } ?>

<?php endwhile; endif; ?>

With this code, any post with a custom-field of “name-of-custom-field” that has a specific value of “name-of-value” will be displayed in its entirety. All other posts will be displayed as an excerpt.

Source: Perishable Press

How to Number Your Comments, Pingbacks, and Trackbacks in 2.7+

Numbering comments, pingbacks, and trackbacks in WordPress versions 2.7 and greater requires two steps. First, you need to add a couple of parameters to your comments_template tag, which is used to display your comments template and normally located in your single.php file. Edit this tag so that it looks like this:

<?php comments_template('/comments.php',true); ?>

Once this is in place, you can display the number of your comments, pingbacks, trackbacks, and both using the following tags:

echo count($wp_query->comments_by_type['comment']); // display comment count
echo count($wp_query->comments_by_type['pingback']); // display pingback count
echo count($wp_query->comments_by_type['trackback']); // display trackback count

echo count($wp_query->comments_by_type['pings']); // display pingback and trackback count

comments_number('No Responses', 'One Response', '% Responses' ); // display total response count

These tags can be placed anywhere in your comments loop. For more information on how to implement this, check out our in-depth article at Digging into WordPress.

How to Number Your Comments Using the Classic Loop

Before, WordPress added the new comments API in version 2.7, the “classic” comment-loop mechanism was used. This loop still works in any version of WordPress, and is useful for extreme formatting of the comment display area. Numbering your comments in the classic loop is as easy as it is in the new-fangled loop. Here’s how:

In your comments.php file, add a counter variable ( <?php $i = 0; ?> ) just above the loop’s foreach statement, like so:

<?php $i = 0; ?>
<?php foreach ($comments as $comment) : ?>

Then, to increment the counter variable with each iteration of the loop, we add another snippet just below the foreach line, like so:

<?php $i = 0; ?>
<?php foreach ($comments as $comment) : ?>
<?php $i++; ?>

Everything is now set. To display the number of comments, simply echo the value of the counter variable anywhere within your comment loop. Here is an example:

<h3>There are <?php echo $i; ?> comments so far!</h3>

Source: Digging into WordPress

Invite Readers to Comment via Feed

Nice little snippet showing how to invite your readers to leave a comment by clicking on a link within your feed. Just add the following code to your theme’s functions.php file:

// comment invite feed link
function rss_comment_footer($content) {
	if (is_feed()) {
		if (comments_open()) {
			$content .= 'Comments are open! <a href="'.get_permalink().'">Add yours!</a>';
		}
	}
	return $content;
}

In place, this function will output a link that says, “Comments are open! Add yours!” This message will be displayed at the end of each post for which comments are open. If comments are closed, no invite message is displayed.

Source: Hendry Lee (404 link removed)

Display the Total Number of Users for Your Blog

Here is a tasty little snippet from WP Recipes that will enable you to display the total number of users for your WordPress-powered blog. All you need to do is place the following code in your theme file(s) where you would like to display your total number of users:

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

Automatically Insert Content into Your WordPress Post Editor

Here is a nice way to automatically insert some custom content into your post editor. This makes it easy to add repetitive content to your posts while retaining the ability to make changes before publishing. To try it out, add the following code to your functions.php file:

<?php // auto-insert content to post editor
function my_editor_content($content) {
	$content = "<h5>Thank you for your generous attention!</h5>.";
	return $content;
}
add_filter('default_content', 'my_editor_content');
?>

This code will display a message thanking people for their generous attention, but you can easily edit the message to display whatever content (text/markup) that you wish. After configuring your message, open your WordPress text editor to see the automatically inserted content.

How to Prevent Duplicate Content

Unless you’re using excerpts for non-single page views, your post content is being displayed in your single pages, date-based archives, category archive, tags archives, author archives, and so on. From an SEO perspective, this “duplicate” content may be detrimental to your search-engine rankings.

To prevent duplicate content, we can conditionally display one of two <meta> tags depending on the type of page being displayed. Pages that we want to have indexed in the search engines will display a “meta-index” tag, while duplicate pages will display a “meta-noindex” tag.

To do this, simply add the following code to the <head> section of your theme’s header.php file:

<?php if ((is_home() && ($paged < 2 )) || is_single() || is_page() || is_category()) {
	echo '<meta name="robots" content="index,archive,follow" />';
} else {
	echo '<meta name="robots" content="noindex,noarchive,follow" />';
}

Once in place, this code effectively stops search engines from indexing all types of pages except for single-post, page-page, category-archive, and the first two index pages. These are considered by many to be the most effective pages to have indexed, but feel free to add or remove anything you see fit to customize the technique.

Source: Perishable Press

Conditionally Display Full Posts or Excerpts

By default, you can either display full-posts or excerpts when displaying your posts. This may be fine for common blogging purposes, but specialized blogs may find it beneficial to exercise control over which type of post format is displayed. Here’s how to conditionally display either full-post or excerpt based on the presence of a custom field named “full-post-display”.

To implement this technique, setup the following loop in your theme file(s):

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php $customdisplay = get_post_custom_values("full-post-display"); ?>

	<?php if (isset($customdisplay[0])) { ?>
              
		<h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
		<?php the_content(); ?>

	<?php } else { ?>

		<h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
		<?php the_excerpt(); ?>

	<?php } ?>
<?php endwhile; endif; ?>

Then, for any post that you would like to display with full-post formatting, simply add a custom-field of “full-post-display” and give it a value of “true”.

Display Related Posts without a Plugin

We don’t need no stinking plugins to display related posts! Here’s how to do the job using tags as the associative criteria.

Place the following code in your loop and take a nap or something:

<?php // related posts based on first tag of current post
$tags = wp_get_post_tags($post->ID);
if ($tags) {

	echo '<h3>Related Posts</h3>';

	$first_tag = $tags[0]->term_id;
	$args = array(
			'tag__in' => array($first_tag),
			'post__not_in' => array($post->ID),
			'showposts' => 7, // how many posts?
			'caller_get_posts' => 1
			);

	$my_query = new WP_Query($args);
  	if ($my_query->have_posts()) { ?>

		<ul>

		<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>

			<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>

		<?php endwhile; ?>

		</ul>

	<?php } ?>
<?php } ?>

Customize as needed. To change the number of posts, edit the line that says, “how many posts?”

Source: Enhanced version of the code provided by MichaelH (via WP Codex)

Drop-Dead Easy Styles for Author Comments

This is almost too easy. To make your Author comments stand out from the crowd in WordPress 2.7 or better, use this code to apply some custom CSS stylez:

li.bypostauthor {
	background: red;
	color: white;
	}
li.byuser {
	background: white;
	color: black;
	}

Display Upcoming Scheduled Posts

Here’s an easy way to display a list of posts that are scheduled to be published at some point in the future. Create a page called “Upcoming Posts” (or whatever), and use this code for the loop:

<?php query_posts('showposts=7&post_status=future'); ?>

<?php if (have_posts()) : ?>

	<h3>Upcoming Scheduled Posts</h3>
	<ul>
	<?php while (have_posts()) : the_post(); ?>

		<li><?php the_title(); ?> — <?php the_time('l, F j, Y'); ?></li>

	<?php endwhile; ?>
	</ul>

<?php else: ?>

	<p>Nothing new in queue!</p>

<?php endif; ?>

In place, this code will output a list of all posts that exist within the database that have a post_status of future. I.e., anything that you have setup in draft mode that is set to auto-publish at a certain point in the future.

Display Automatic TinyURLs for Your Posts

Make it super-easy for your visitors to share the URL of your posts with their favorite social-media service. Providing an alternate “short” version of your URLs is possible using the free TinyURL service and a couple snippets of code.

To display short URLs at the end of your posts, place this code into your theme’s functions.php file:

function getTinyUrl($url) {
	$tinyurl = file_get_contents("http://tinyurl.com/api-create.php?url=".$url);
	return $tinyurl;
}

Then, call the function and display the URL by placing this code into your single.php file in the desired location within the loop:

<?php $turl = getTinyUrl(get_permalink($post->ID)); 
echo 'TinyURL for this post: <a href="'.$turl.'">'.$turl.'</a>'; ?>

That’s it! Your posts now feature super-short URLs for all of your tweet-hungry visitors. Tuper Tweet Tude!

Source: Perishable Press

Implement a Site-Maintenance Page for Your Blog

Ever do maintenance on your site? Certainly, we all do. Here’s an easy way to display a “site-maintenance” page that will display whatever content you desire. The key here is setting up your HTAccess file to handle the redirect properly.

First, you need to create your maintenance page. This can be as simple or as advanced as you would like. At minimum, you could include something like this into a file named “maintenance.html”:

<h1>Site Maintenance</h1>
<p>Please check back in 15 minutes</p>

Then, add this bit of voodoo to your site’s root htaccess file:

# SITE MAINTENANCE PAGE
RewriteEngine on
RewriteCond %{REQUEST_URI} !/maintenance.html$
RewriteCond %{REMOTE_ADDR} !^111\.222\.333\.444
RewriteRule $/maintenance.html [R=302,L]

Once that’s in place, replace the example IP address with that of your own. Upload to your site and check it out. What you will see is that you have full access to your site, but all other visitors will see the maintenance page.

Once maintenance is complete, simply comment out the code in your htaccess file to allow visitors back into the site.

Source: WP-Mix.com

Display the First Image from Each of Your Posts

If your posts include an image that you would like to display as a thumbnail elsewhere on your blog, here is an easy way to do it with no custom fields required. Place the following code into your theme’s functions.php file:

function catch_that_image() {
	global $post, $posts;
	$first_img = '';
	ob_start();
	ob_end_clean();
	$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
	$first_img = $matches [1] [0];

	if(empty($first_img)){
		$first_img = "/images/default.jpg"; // default image
	}  
	return $first_img;
}

Then, to call the function and display the images as thumbnails, place the following code into the desired location within your loop:

<?php echo catch_that_image(); ?>

That’s all there is to it. If you would like to display a default image for posts that may not have one, specify its path in the code (on the line that says “default image).

Display Most Popular Posts without a Plugin

Simple but effective method of displaying your blog’s most popular posts based on comment count. This code snippet may be placed anywhere within your theme’s files (i.e., no loop required). Check it out:

<h3>Popular Posts</h3>
<ul>
<?php $result = $wpdb->get_results("
	SELECT comment_count, ID, post_title 
	FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 , 7
	");

foreach ($result as $post) {
	setup_postdata($post);
	$postid = $post->ID;
	$title = $post->post_title;
	$commentcount = $post->comment_count;
	if ($commentcount != 0) { ?>

	<li><a href="<?php echo get_permalink($postid); ?>">
	<?php echo $title; ?></a> [<?php echo $commentcount ?>]</li>

	<?php } ?>
<?php } ?>
</ul>

Once in place, this code will display the seven most popular posts along with their associated comment count in unordered list format. Customize according to your needs.

Automatically Highlight Search Terms

Make things easy for people who are searching your site by applying some custom styling to the search terms that are displayed in the search results. A common way to display search terms is with a yellow background so that users can easily identify locations of the text that may apply to their query. It’s all about about usability, and improving the way search results are displayed on your site. Here’s how to do it:

First, replace the the_title() tag in your search.php file with the following:

<?php // highlight search terms in title
	$title = get_the_title();
	$keys  = explode(" ", $s);
	$title = preg_replace('/('.implode('|',$keys).')/iu','<span class="search-terms">\0</span>',$title);
	echo $title;
?>

This will setup styling for search terms located in the title of each result. Then, for the content, replace the the_excerpt() tag in your search.php file with the following:

<?php // highlight search terms in content
	$excerpt = get_the_excerpt();
	$keys  = explode(" ", $s);
	$excerpt = preg_replace('/('.implode('|',$keys).')/iu','<span class="search-terms">\0</span>',$excerpt);
	echo $excerpt;
?>

Finally, open your theme’s CSS file and add some custom styles for the search terms. A great way to highlight each term is to display it in bold text with yellow highlighting. Something like this:

span.search-terms { 
	background: yellow;
	font-weight: bold;
	}

That’s all there is to it! Go run a few searches to see it in action.

Source: Enhanced version of code provided by Yoast.com

Automatically Disable Widgets

Quick tip to disable all widget functionality from your theme. Add the following to your functions.php file and call it done:

<?php // disable all widgets
function disable_all_widgets($sidebars_widgets) {

	$sidebars_widgets = array(false);
	return $sidebars_widgets;

}
add_filter('sidebars_widgets', 'disable_all_widgets');
?>

Display All Images from Your Post Content

Want to display all of the images from each of your posts somewhere on your blog? Easy. Check out this code snippet from Matt Varone:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

<?php 
$szPostContent = $post->post_content;
$szSearchPattern = '~<img [^\>]*\ />~';

// Run preg_match_all to grab all the images and save the results in $aPics
preg_match_all($szSearchPattern, $szPostContent, $aPics);

// Check to see if we have at least 1 image
$iNumberOfPics = count($aPics[0]);

if ($iNumberOfPics > 0) {
	// now here you would do whatever you need to do with the images
	// for this example the images are just displayed
	for ( $i=0; $i < $iNumberOfPics ; $i++ ) {
		echo $aPics[0][$i];
	};
};

endwhile;
endif;
?>

Just customize the output in the second part of the code (see code comments) and paste the function wherever you would like to display the images. Sweetness.

Display Category List in Two Columns

Tired of that boring, single-column category display? Spice things up with a spiffy two-column category list that will get your visitors’ hearts pumping. Let’s deface a WordPress tag, shall we?

See this bad boy:

<?php wp_list_categories(); ?>

We’re going to blow it up, divide its contents into two pieces, and spit it all back out as two unordered lists. Impossible, you say? Nah, just a little PHP to make it all go.

Wherever you would like to display your categories in two columns, throw down the following code snippet:

<?php // display categories in columns
$cats = explode("<br />",wp_list_categories('title_li=&echo=0&depth=1&style=none'));
$cat_n = count($cats) - 1;
for ($i=0;$i<$cat_n;$i++) :
	if ($i<$cat_n/2) :

		$cat_left = $cat_left.'<li>'.$cats[$i].'</li>';

	elseif ($i>=$cat_n/2):

		$cat_right = $cat_right.'<li>'.$cats[$i].'</li>';

	endif;
endfor; ?>

<ul class="left">
	<?php echo $cat_left;?>
</ul>
<ul class="right">
	<?php echo $cat_right;?>
</ul>

Completely awesome. Now let’s add some style to make the columns work:

.right {
	float: left; 
	width: 140px;
	}
.left {
	float: left; 
	width: 140px;
	}

You are all set. You should probably fine-tune this business until it’s all good. You know.

Show Ads or Other Content Only in the First Three Posts

Advertising may require you to limit the number of advertisements on your page to three. For some, this is three too many. For others, it’s far too few. Still others feel that it’s just the right amount.

Regardless of your feelings, here is a trick that will enable you to limit the number of posts that displays some specific content — ads, images, scripts, whatever you want. Check out the three indented lines in the following loop:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

	<?php if ($wp_query->current_post < 3) { ?>

	<!-- any content here will be displayed only in first three posts -->

	<?php } ?>

<?php endwhile; else: ?>
<?php endif; ?>

See what’s happening here. We’ve got a loop, see. In this loop, we specify a condition that says, “if this is one of the first three posts, display this content.” And that’s the magic. Of course, you can use whatever content you would like, and there is nothing special about the number 3 either.

A Better Way to Display Recent Comments without a Plugin

Here is a better way to display your recent comments without a plugin. Instead of slapping a bunch of gnarly code into our index.php or sidebar.php file, we are going to slap it right where it belongs: in your theme’s functions.php file.

Here is the code, all exploded for your viewing and analytical pleasure (well, for mine anyway). For a more minified version of this snippet, be sure to check out the source link.

<?php // display recent comments without a plugin

function recent_comments($src_count=10, $src_length=60, $pre_HTML='<ul>', $post_HTML='</ul>') {
global $wpdb;
$sql = "
	SELECT DISTINCT 
		ID, 
		post_title, 
		post_password, 
		comment_ID, 
		comment_post_ID, 
		comment_author, 
		comment_date_gmt, 
		comment_approved, 
		comment_type, 
	SUBSTRING(
		comment_content, 1, $src_length
		) 
	AS com_excerpt 
	FROM $wpdb->comments 
	LEFT OUTER JOIN $wpdb->posts 
	ON (
		$wpdb->comments.comment_post_ID = $wpdb->posts.ID
		) 
	WHERE comment_approved = '1' 
	AND comment_type = '' 
	AND post_password = '' 
	ORDER BY comment_date_gmt 
	DESC
	LIMIT $src_count
";
$comments = $wpdb->get_results($sql);
$output = $pre_HTML;

foreach ($comments as $comment) {

	$output .= '<li><a href="'.get_permalink($comment->ID).'#comment-'.$comment->comment_ID.'" title="on '.$comment->post_title.'">'.strip_tags($comment->com_excerpt).'...</a></li>';

}
$output .= $post_HTML;
echo $output;

} ?>

Ah, it’s a thing of beauty. Once you have that code in place, rock it out anywhere in your theme with this charming little tag:

<?php recent_comments(); ?>

See also: Display Latest Comments without a Plugin

Selectively Disable Automatic Post Formatting

This trick is by far my favorite “stupid WordPress trick.” You know how WordPress likes to mangle HTML comments, empty elements, blockquotes, curly quotes, and other miscellaneous markup elements? Here is a tight little method that will enable you to selectively disable WordPress’ automatic post formatting.

Do this: Place the following code into your theme’s functions.php file:

// disable auto-formatting
function my_formatter($content) {
	$new_content = '';
	$pattern_full = '{(\[raw\].*?\[/raw\])}is';
	$pattern_contents = '{\[raw\](.*?)\[/raw\]}is';
	$pieces = preg_split($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE);

	foreach ($pieces as $piece) {
		if (preg_match($pattern_contents, $piece, $matches)) {
			$new_content .= $matches[1];
		} else {
			$new_content .= wptexturize(wpautop($piece));
		}
	}
	return $new_content;
}
remove_filter('the_content', 'wpautop');
remove_filter('the_content', 'wptexturize');
add_filter('the_content', 'my_formatter', 99);

Then do this: Use the [raw] shortcode wherever you would like to disable auto-formatting in your post content. For example, if you wanted to prevent the following sentence from being formatted, you would write this:

[raw]This text will not be automatically formatted.[/raw]

Absolutely brilliant.

Browser Detection via WordPress’ body_class Function

WordPress makes it possible to detect a handful of different browsers using a variety of built-in global variables. WordPress also provides a body_class tag that outputs a variety of class attributes depending on various page properties. Why not combine these two techniques so that the user’s detected browser is added to the list of output classes for the body tag? Here’s the code that will do it via functions.php:

// browser detection via body_class
function browser_body_class($classes) {

    global $is_lynx, $is_gecko, $is_IE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone;

    if($is_lynx)       $classes[] = 'lynx';
    elseif($is_gecko)  $classes[] = 'gecko';
    elseif($is_opera)  $classes[] = 'opera';
    elseif($is_NS4)    $classes[] = 'ns4';
    elseif($is_safari) $classes[] = 'safari';
    elseif($is_chrome) $classes[] = 'chrome';
    elseif($is_IE)     $classes[] = 'ie';
    else               $classes[] = 'unknown';

    if($is_iphone) $classes[] = 'iphone';
    return $classes;

}
add_filter('body_class','browser_body_class');

This code will output the detected browser along with the other body_class tags. Here is an example:

<body class="home blog logged-in safari">

Hooked.

Sources: Nathan Rice

Get Post or Page Contents as a PHP Variable

Here is a quick snippet for placing all post or page content into a variable. We’re talking the entire page contents here, not just the content of the post. Place this code into your theme’s functions.php file:

// post contents as variable
function callback($buffer) {
	return $buffer;
	}
function buffer_start() {
	ob_start("callback");
	}
function buffer_end() {
	ob_end_flush();
	}
add_action('wp_head', 'buffer_start');
add_action('wp_footer', 'buffer_end');

Once in place, this function will capture the entire page contents into a variable called $buffer. You may then do whatever you wish to this variable. Filter it, match it, slap it around a little and show it who’s boss. That sort of thing.

Source: Dagon Design

See also: Digging into WordPress

Simple Example of How to Use WordPress Cron

I have been meaning to get into WordPress’ wp-cron functionality, and this looks like a good way to get started with it. This code snippet uses wp-cron to schedule an automatic email that will be sent every hour.

// send automatic scheduled email
if (!wp_next_scheduled('my_task_hook')) {
	wp_schedule_event(time(), 'hourly', 'my_task_hook');
}
add_action('my_task_hook', 'my_task_function'); 

function my_task_function() {
	wp_mail('you@yoursite.com', 'Automatic email', 'Hello, this is an automatically scheduled email from WordPress.');
}

Of course, this is meant only as an example. The key here is to schedule and event and then hook into it with some specific function.

Add More Default Avatar Choices to the WordPress Admin

Here is a quick and easy way to add more default avatars to the list of available gravatars in the Settings area of the WordPress Admin. Here is the functions.php code to make it happen:

// add more default avatars to options
if (!function_exists('fb_addgravatar')) {
	function fb_addgravatar($avatar_defaults) {

		$myavatar1 = get_bloginfo('template_directory').'/images/avatar-01.png';
		$avatar_defaults[$myavatar1] = 'dude';
 
		$myavatar2 = get_bloginfo('template_directory').'/images/avatar-02.png';
		$avatar_defaults[$myavatar2] = 'geek';
 
		$myavatar3 = get_bloginfo('template_directory').'/images/avatar-03.png';
		$avatar_defaults[$myavatar3] = 'cool';

		return $avatar_defaults;
	}
	add_filter('avatar_defaults', 'fb_addgravatar');
}

See the innermost indented lines of code? There we are specifying three additional default avatars. To use this code, you will need to edit these lines to match your image paths and the name for each avatar. Hopefully the process of editing, adding, or removing avatars is clear. If not, don’t hesistate to speak up in the comments and someone will help you out.

Source: WPEngineer

Add a Private Page to Your Navigation Menu

By default, any pages that you classify as “Private” are not displayed in the menu generated by the wp_list_pages function. In general this is a good idea, but it might be helpful to include the link if the logged in user is able to read private pages. Fortunately, WordPress has a function that will enable us to do exactly that:

<ul>
<?php // add a private page to your navigation menu
wp_list_pages('depth=1&title_li=0&sort_column=menu_order');
if(current_user_can('read_private_pages')) : ?>

	<li><a href="<?php echo get_permalink(10); ?>">For Authors only</a></li>

<?php endif; ?>
</ul>

Place this code where you would normally include the wp_list_pages tag and enjoy private-page links displayed in your navigation menus only for those users who are logged in and priviledged enough to see them. The private link will not be displayed for the “ordinary” folk.

Make sure you replace the number 10 in the middle line to match the ID of the private page you would like to include.

Source: WPEngineer

How to Add Additional Links to wp_list_pages

Here is a nice way to include additional links to the output of the wp_list_pages tag. All that’s needed is the following function in your functions.php file:

// include additional links
function add_bookmarks_to_menu($output) {
	$bookmarks = (array) get_bookmarks('hide_invisible=0&category_name=wp_list_pages');
	foreach ($bookmarks as $bookmark) {
		$output .= "<li><a href='{$bookmark->link_url}'  title='{$bookmark->link_name}'>{$bookmark->link_name}</a></li>\n";        

	}
	return $output;
}
add_filter('wp_list_pages', 'add_bookmarks_to_menu');

Here we are taking advantage of WordPress’ built-in Links/Bookmarks functionality to assign new links to the output of the wp_list_pages tag. Once this code is in place, login to your WordPress Admin and follow these steps for each link that you would like to add to the page list:

  1. In the Admin, go to Links > Add New
  2. Enter a name and URL for your link
  3. Add the link to a new category called “wp_list_pages”
  4. select “Keep this link private”
  5. Click “Add Link”
  6. Done.

Using the “wp_list_pages” category for any/all of our extra links will enable us to include only links from that category. Further, selecting the “Keep this link private” option will prevent the links from being displayed elsewhere in your site (for example, in the Links/Blogroll/Bookmark sections).

“I’ve got blisters on my fingers!”

..as the man once said.

About the Author
Jeff Starr = Web Developer. Security Specialist. WordPress Buff.
Digging Into WordPress: Take your WordPress skills to the next level.

55 responses to “Stupid WordPress Tricks”

  1. AAARRRRRRRGGGGGGGGHHHHHH!!!!! The Awesomeness!! It hurts my eyeeeesssssss!!!!!!!!!!!!!!!!!

  2. Alex Denning 2009/12/01 2:02 pm

    That is one heck of a list Jeff! Really useful to have *everything* in one place :D

  3. Hal Brown 2009/12/01 2:34 pm

    This is great! Thanks for the work that must have gone into putting all this together. Much appreciated.

  4. This article has been shared on favSHARE.net. Go and vote it!

  5. John (Human3rror) 2009/12/01 7:12 pm

    omg. this post is so epic.

  6. Wow, can someone tell me where I can find the printable version? This article is a must read.

  7. Jeff Starr 2009/12/01 6:34 pm

    Thanks for the great feedback, everyone :)

    @Jens: compared to the book, Digging into WordPress, this article is nothing — just the leftover scraps that were too juicy to throw away :)

  8. Senthil Ramesh 2009/12/01 9:09 pm

    That must be a all in one tut. And I cant leave without bookmarking this article.

  9. Shurandy Thode 2009/12/01 8:37 pm

    Nice compilation here! Thnx for sharing. =)

  10. Andrew Tan 2009/12/01 10:27 pm

    Nice collection you have there. Thanks for sharing and I likeeee… the way you present. Good work!

  11. Julia Altermann 2009/12/01 11:29 pm

    Jaw-dropping amazing! How long did it take you to compile and write this post?

    Thank you so much for the work you put into this, this must be the one of the best WordPress related posts ever! Will take quite some time to digg through it, but it really is worth it.

    Thanks!

  12. Awesome man.Bookmarked

Comments are closed for this post. Something to add? Let me know.
Welcome
Perishable Press is operated by Jeff Starr, a professional web developer and book author with two decades of experience. Here you will find posts about web development, WordPress, security, and more »
GA Pro: Add Google Analytics to WordPress like a pro.
Thoughts
I disabled AI in Google search results. It was making me lazy.
Went out walking today and soaked up some sunshine. It felt good.
I have an original box/packaging for 2010 iMac if anyone wants it free let me know.
Always ask AI to cite its sources. Also: “The Web” is not a valid answer.
All free plugins updated and ready for WP 6.6 dropping next week. Pro plugin updates in the works also complete :)
99% of video thumbnail/previews are pure cringe. Goofy faces = Clickbait.
RIP ICQ
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.