Stupid WordPress Tricks


Stupid WordPress Tricks

[ WordPress ]One of the most popular articles here at Perishable Pressis 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 theirHTAccess 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 onlyscratching 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 Posts 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 '';
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) {
		"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=""]Perishable Press[/link]

..which will output the following code:

<a href="">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>

Source: Julien Chauvin (404 link removed 2013/06/27)

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

Source: ifohdesigns (404 link removed 2012/09/14)

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:


$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>

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>';

} ?>

<?php endif; ?>

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

Source: Corey (404 link removed 2014/06/08)

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() {

	$SE  = array('/search?', '', '', 'search.', '', '', '/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()) {


} ?>

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

Source: Kyle Eslick

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.


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:

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

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(); ?>
	<?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; ?>
<?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:

<?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>'; 

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.

Source: Matt Varone (404 link removed 2015/02/26)

Display List of Scheduled Posts

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

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

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 oftrue. 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:

$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>

<?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:

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

Source: Fred jaillet [via]

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 thenext/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(); ?>
	<div class="navigation">
		<div class="alignleft"><?php previous_comments_link(); ?></div>
		<div class="alignright"><?php next_comments_link(); ?></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';
	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.

Source: Justin Tadlock

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 */ 

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_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’scomments-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’sfunctions.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’sheader.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.

Source: Malcolm Coles (404 link removed)

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:

} else {

	// this post has no excerpt, so display something else instead:

} ?>

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:


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:

	<?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(); ?>
	<php endforeach; ?>

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.

Credit: WordPress Garage (404 link removed 2014/10/22)

Automatically Remove Code Mistakes in Posts

Here is a handy trick that will automatically remove basic mistakes in XHTMLmarkup, 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.

Credit: Matt Varone (404 link removed 2015/02/26)

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 EngineerPlugin: 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')) {
} elseif (in_category('2')) {
} else {
} ?>

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(); ?>">

After changing the email address to that of your own (i.e., the one used for your WPAdmin 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(); ?>">

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

Credit: Nyssa Brown (404 link removed)

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:


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()";
			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:

// 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 commentswithout 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, 
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 

$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) 
$output .= "\n</ul>";
$output .= $post_HTML;

echo $output;

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

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

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

Source: StylizedWeb (404 link removed 2015/03/12)

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:

$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 } } ?>

This code may be modified to display any number of posts by changing the LIMITfrom “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:

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

Source: StylizedWeb (404 link removed 2015/03/12)

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%/ this:


This change will ensure that all future posts are located at the new post-name-onlyURL, but we still need to redirect all requests for existing posts via the old date-basedURL format. This is easily accomplished with a single directive in your site’s rootHTAccess 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()) : ?> 
	<?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; ?>
<?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') {
} else {
} ?>

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>


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:

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

	<p>Today is <a href="">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 someHTML comments:

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


This content will appear in the first column.


This content will appear in the second 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 ofHTML 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 FALSEwill 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 yourcomments_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:

There are comments so far!

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.phpfile:

// 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

Display the Total Number of Users for Your Blog

Here is a tasty little snippet from WPRecipes 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.

Source: Justin Tadlock

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’sheader.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()) { ?>


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

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

		<?php endwhile; ?>


	<?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>
	<?php while (have_posts()) : the_post(); ?>

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

	<?php endwhile; ?>

<?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’sfunctions.php file:

function getTinyUrl($url) {
	$tinyurl = file_get_contents("".$url);
	return $tinyurl;

Then, call the function and display the URL by placing this code into your single.phpfile 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:

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: Catswhocode

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 = '';
	$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
	$first_img = $matches [1] [0];

		$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).

Source: WPRecipes

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>
<?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) {
	$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 } ?>

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.

Source: ProBlogDesign (404 link removed 2013/09/15)

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"></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"></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: { 
	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

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');

Source: Justin Tadlock

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(); ?>

$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];


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.

Source: Matt Varone (404 link removed 2015/02/26)

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>';

endfor; ?>

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

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.

Source: Blog Oh Blog (404 link removed 2013/06/24)

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.

Source: Blog Oh Blog (404 link removed 2013/06/24)

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 = "
		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 
	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 PluginSource: Blog Oh Blog (404 linkremoved 2013/06/24)

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.

Source: WPRecipes

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;


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


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() {
function buffer_end() {
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 DesignSee 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('', '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.

Source: (404 link removed 2013/02/04)

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.phpcode 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:

<?php // add a private page to your navigation menu
if(current_user_can('read_private_pages')) : ?>

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

<?php endif; ?>

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!” the man once said.

Related posts:
  1. WordPress Custom Fields, Part II: Tips and Tricks
  2. Display the Total Number of WordPress Posts, Comments, and Categories
  3. Stupid Twitter Tricks
  4. Easily Adaptable WordPress Loop Templates
  5. Fruit Loop: Separate any Number of Odd and Even Posts from any Category in WordPress
Instant karma



Share with others

About this post
Check it out

The Tao of WordPress


« Previous 13 4 5

  1. PatrixJanuary 5, 2010 at 8:54 pm

    Awesome post.

    My theme lacks a functions.php file. When I created one and uploaded it, it was populated by some functions that I did not recognize. When I added one of the codes you mentioned above, I got an error saying, Headers Already Sent or something like that.

  2. Actu-RockJanuary 6, 2010 at 2:04 pm

    Really useful! Thanks

  3. Lee PetersonJanuary 11, 2010 at 5:13 pm

    4 hours later….

    Finally reached the end. Thanks for the awesome roundup!!

  4. MaxenceJanuary 22, 2010 at 6:50 am

    Best wordpress tricks page! Kind of link that everyone should Bookmark thanks you very much for sharing this, this is gonna save my life!

  5. Steve G.January 24, 2010 at 1:39 pm

    This collection of WordPress Tricks is very useful. Thank you for sharing all this!

  6. shoaib hussainFebruary 11, 2010 at 8:12 am

    thnx a lot ,had 2 bookmark so that i could grab more fun later on

  7. MarkFebruary 12, 2010 at 11:46 am

    Very usefull article! Thanks!

« Previous 13 4 5

Comments are closed. Contact the author with questions or further information.

« Getting Serious with a New Design

The New Clearfix Method »

Stupid WordPress Tricks

Extending WordPress with Functions.php

Some WordPress themes contain one PHP file that isn’t a template, named functions.
php. Experienced theme designers place important parts of their code here, and
then call that code from their template files when they need it. WordPress gurus also
use the functions.php file to add other features, like new shortcodes and widgets,
so they don’t need to create a complete plug-in.
All these tasks are advanced operations, best kept to WordPress gurus. However,
even people with no PHP experience can use the functions.php file to unlock extra
WordPress features. Usually, you do that by copying a few lines of code you read
about online (or in a book), and pasting them into the functions.php file in the
theme editor.
For example, in Chapter 10, you used WordPress’s auto-embed feature to turn certain
types of website addresses into embedded objects, like Flickr slideshows and
YouTube videos. Normally, WordPress turns off this handy feature in widget areas,
like the sidebar. But those in the know can enable shortcodes and embeds in widget
areas with just a couple of lines in the functions.php file. Figure 13-18 shows the result.
The functions.php file works a bit differently from the template files you’ve learned
about so far. The key quirk is that the functions.php file in your child theme extends
the functions.php file in your parent theme; it doesn’t replace it. For that reason, you
can’t simply copy the functions.php file from your parent theme to your child theme.
You need to create a new, empty text file on your computer, change its name to
functions.php, and then upload that new functions.php file to your child theme folder.
If you use the Orbisius Child Theme Creator plug-in, your job is easy. Follow the
process described on page 490 to create a new, blank functions.php file, but don’t
copy any content to that file.

WARNING If you accidentally copy the functions.php file from your parent theme to your child theme,
your site will stop working. That’s because functions.php is full of important routines that Twenty Twelve uses,
and having two copies of this code is enough to blow WordPress’s mind. The only fix (if you disregard this warning
and put the full functions.php file in your child theme folder) is to log in to your site with an FTP program and
delete the copied functions.php file.
Once you add the blank functions.php file to your site, you can edit it in the Edit
Theme page, as you can any other theme file. To enable widget-embedding, as
shown in Figure 13-18, you need to add these lines:

add_filter( ‘widget_text’, array( $wp_embed, ‘run_shortcode’ ), 8);
add_filter( ‘widget_text’, array( $wp_embed, ‘autoembed’), 8 );

Now you can put an auto-embed URL in a Text widget, just as you can in a post

Extending WordPress with Functions.php

A Basic Editing Example

By this point, you’ve digested a fair bit of WordPress theory. It’s time to capitalize
on that by editing a template file.
You’ll begin with an example that seems simple enough. You want to remove the
“Proudly powered by WordPress” message that appears at the bottom of every
page on your site, just under the footer widgets (Figure 13-15). (It’s not that you’re
embarrassed by WordPress. You just can’t help but notice that none of the other
big-gun WordPress sites have this message slapped on their pages. Sometimes,
being professional means being discreet.)

Start by examining the list of templates in Table 13-2. In this case, the footer.php
file is the obvious candidate. It creates the entire footer section, widgets and all,
for every page.

Once again, you need to start with a child theme (page 462). If you don’t, you can
still customize the footer, but your hard-won changes will vaporize the moment you
install a theme update.
Here’s where things get a bit more awkward. As you know, WordPress templates are
really a collection of many template files. To change a template, you need to figure
out the changes you want to make to your pages, and then find the template file
responsible for that part of the page (single.php, comment.php, and so on). Then
you add a new version of that template file to the child theme. That new template
will override the one in the parent theme.
You do this by copying the template file you want to edit from the parent theme to
your child theme and then making your changes. In this example, that means you
need to copy the footer.php file in the twentytwelve folder and paste it into the
twenty-twelve-reboot folder.

NOTE The child theme’s version of a template completely overrides the parent theme’s copy of the template.
In this example, that means WordPress ignores the original version of the footer.php file, which is in the original
theme folder (twentytwelve). You can refer to it anytime to check the code or copy important bits, but WordPress
won’t run the code anymore.

Footer.php is one of WordPress’s simpler template files. But even simple templates
have a fair bit of boilerplate to wade through.
In this section, you’ll look at the entire contents of footer.php. You don’t always need
to take this step, but it’s good practice when you’re just starting out and trying to
make sense of WordPress’s template system.
If you’ve written web pages before, you probably know that programming code,
like JavaScript, needs to be carefully separated from the HTML on the page. The
same is true for PHP, although it has its own special syntax. Every time a block of
PHP code appears, it starts with this:
Similarly, the following character sequence marks the end of a block of PHP code:
You can see this system at work at the very beginning of every template file, where
there’s a block of PHP that has no real code at all, just a long comment. The comment
lists some basic information about the template. Here’s what you see in footer.php:
* The template for displaying the footer.
* Contains footer content and the closing of the #main and #page div elements.
* @package WordPress
* @subpackage Twenty_Twelve
* @since Twenty Twelve 1.0
The next line is a puzzling bit of HTML that looks like this:
</div><!– #main .wrapper –>
Even seasoned HTML veterans will be a bit thrown off here. The </div> tag closes
a <div> element. But you haven’t seen an opening <div> tag, so this code snippet
seems a bit strange.
It makes more sense when you remember the way WordPress stitches together a
page, as shown in Figure 13-14. The <div> element was opened, but it happened when
WordPress processed an earlier template file (header.php). The HTML comment in
the line above (<!–#main .wrapper –>) is WordPress’s way of reminding you that
the </div> in that line is the closing element for a <div> that has the ID main and
the class .wrapper. In other words, it’s the closing element for the <div> that holds
the main content of the page.

The next line of HTML is easier to interpret. It identifies the beginning of the footer
content. This section has the ID colophon, which you might remember from Table 13-1.
<footer id=”colophon” role=”contentinfo”>
The next line starts a new <div> element and gives it the ID site-info. The creators of
the Twenty Twelve theme chose that name because this is the section of the page
that indicates some basic information about how the site was created (in other
words, “Proudly powered by WordPress”).
<div id=”site-info”>
The next bit is another block of PHP code, but it’s compressed into a single line:
<?php do_action( ‘twentytwelve_credits’ ); ?>
The do_action() function is a WordPress feature found throughout its template
files. It’s a notification mechanism—it signals when something is about to happen
(for example, that the page credits are about to be shown). Hardcore WordPress
developers can write instructions that react to one of these notifications, but the
do_action() function is no help in your mission to change the footer.
NOTE A function is a block of programming code stored somewhere other than the page it appears on.
WordPress is full of useful functions, and do_action() is one of many. To browse the full catalog of functions
and find out what they do, visit
The section that appears after the do_action() function is the part of the footer
template you’ve been looking for. It’s a link that displays the “Proudly powered”
<a href=
“<?php echo esc_url( __( ‘’, ‘twentytwelve’ ) ); ?>”
title= “<?php esc_attr_e( ‘Semantic Personal Publishing Platform’,
‘twentytwelve’); ?>” rel=”generator”>
<?php printf( __( ‘Proudly powered by %s’, ‘twentytwelve’ ),
‘WordPress’); ?>
The markup looks a bit complicated, because there are three PHP code statements
embedded inside the <a> element. The first one generates the actual link address,
the second one generates the title, and the third one generates the text inside the
<a> element. You don’t need to understand exactly how these statements work to
realize that this is the part you want to change. But first, scan through the rest of
the footer template to make sure you understand what’s going on.
It’s pretty straightforward. First, footer.php closes the <div> and <footer> elements.
Then it closes another <div> that represents the entire page.
</div><!– .site-info –>
</footer><!– #colophon –>
</div><!– #page –>

Next, the footer template triggers WordPress’s wp_footer() function.
<?php wp_footer(); ?>
This is a bit of WordPress infrastructure. Many plug-ins wait for this call and then
do something important. Removing this line can cause those plug-ins to break, so
it’s best to leave it in, even though it isn’t doing anything right now.
Finally, the template closes the <body> and <html> elements, proving that you
have really and truly reached the end of the page. WordPress won’t call any more
templates into action, or add any more content after this point.
Now you’ve found the culprit—the piece of the WordPress template you want to
change. In this example, it’s a single <a> element.
You could delete the <a> element completely, or you can replace it with some text
of your own, like this:
&copy; Copyright 2014 Magic Tea House
The &copy; is a character entity, an HTML code that inserts a special character—in
this case, a copyright symbol.
If you consider yourself a bit of a PHP whiz, you can get fancier in your footer. For
example, instead of sticking in the current year for the copyright notice, you could
ask PHP to do that for you.
First, you need to explicitly tell WordPress that you need PHP’s help. You do that by
adding the <?php and ?> character sequences. You’ll put your code inside.
&copy; Copyright <?php [ Your code goes here. ] ?> by Magic Tea House
Next, you need a PHP command. In this case, it’s the trusty echo command, which
means (in PHP language) “take the result of the next statement, and spit it out onto
the page.”
&copy; Copyright <?php echo ?> by Magic Tea House
But what exactly do you want to spit out? That’s the current date, which you can fetch
with the help of a function built into the PHP language, called date(). Unsurprisingly,
the date() function displays the current date. But by supplying the capital letter Y,
you tell the date() function that you’re interested only in getting the current year.
&copy; Copyright <?php echo date(‘Y’); ?> by Magic Tea House
Like every line of PHP code, you indicate the end of a statement by adding a semicolon
at the end (;)
This completes the example, and drives home a clear point: Even the most straightforward
theme-editing tasks require a bit of slogging.

TIP Since the changes you need to make to the footer.php template are relatively small in this example, it’s
easy enough to do all your editing in the dashboard. For more significant changes, you may want to copy the
theme file to a text editor on your computer, work with it there, and then copy it back to the Edit Themes page
when you finish. And if you decide to edit a theme on your computer, it’s worth considering a text editor that has
a few more frills. For example, Windows users can grab the free Notepad++ program (http://notepad-plus-plus.
org), which uses color-coded text to distinguish the different ingredients in PHP code.

A Basic Editing Example

Delving into the Loop

WordPress experts talk in hushed tones about “the loop,” which is the heart of
WordPress. Its job is to fetch content from your website’s database, one piece at a
time, until it reaches the post limit (that’s the “Blog pages show at most” option in
the Settings→Reading section of the dashboard).
The loop appears in many templates. WordPress uses it to create the main list of
posts on the home page (index.php), the list of results after a search (search.php),
and the list of articles you see when you browse by category, tag, author, or date
(category.php, tag.php, author.php, and date.php, or archive.php when one of
the former is missing). The loop even appears on Twenty Twelve’s showcase page
(showcase.php), twice—first to grab the featured posts that it puts up top, and again
to grab the recent posts that it shows underneath.

In the following example, you’ll take a look at the loop in the index.php file and
change the way it works by adding a new feature: the ability to highlight recent

Your first task is to prepare your template. You can copy the index.php file into your
child theme folder using an FTP program, or you can use the Orbisius Child Theme
Creator plug-in to copy it for you.

The next step is to dig through index.php to get a handle on what’s going on and
what area you need to change. Overall, index.php has this structure:

<?php get_header(); ?>
<div id=”primary”>
<div id=”content” role=”main”>
[ The stuff for displaying posts goes here. ]
</div><!– #content –>
</div><!– #primary –>
<?php get_sidebar(); ?>
<?php get_footer(); ?>

This boils the template down to its essentials. As you can see, the template calls
other templates to create the page’s header, sidebar, and footer. In the middle of
this action are two <div> elements, and inside them is the heart of the index.php
template and the loop. This is the part you’ll focus on.
The first ingredient here, inside the <div> elements, is a block of conditional logic—
code that tests a condition, and takes different actions depending on whether that
condition is true or false. Essentially, the template here uses PHP to ask a question:
Are there any posts?
Here’s how the template structures the conditional logic:

<?php if ( have_posts() ) : ?>
[ If there are posts, you end up here. ]
<?php else : ?>
[ If there are no posts, this section shows the “sorry” message.]
<?php endif; ?>

The have_posts() function gets the answer to the question, “Are there any posts?”
If there are, the condition is true, and the first section springs into action. That’s the
part you’re interested in. (If there aren’t any posts, the condition is false, and you can
let the template handle it in the usual fashion, by showing an apologetic message.)
So what takes place inside the first section, which runs as long as your site has at
least one post? The code starts by adding a navigation link, if necessary. This is the
link that appears before the post list and lets visitors step forward to newer posts.
(If your guest is already viewing the most recent post, this link doesn’t show up.)
Then the code triggers the loop (shown here in bold), and ends by inserting another
navigation link—the one that lets readers step back to see older posts.

<?php twentytwelve_content_nav( ‘nav-above’ ); ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( ‘content’, get_post_format() ); ?>
<?php endwhile; ?>
<?php twentytwelve_content_nav( ‘nav-below’ ); ?>

The actual loop comes down to just three lines. The while and endwhile commands
delineate the start and end of the loop. As long as you have posts, the loop keeps
running. Every time it runs, it grabs a post, using the WordPress function the_post(),
and feeds it to the single line of code inside. This code is less exciting—it simply farms
out the work of displaying the post to one of the content templates you learned
about earlier, using the get_template_part() function.
Although the code doesn’t seem that exciting right now, there’s a lot you can do
if you wedge yourself inside the loop, between the while and endwhile lines. Currently,
there’s just a single line of code there, but you can expand it to suit your
needs. For example, before the code calls get_template_part() to display a post,
you can run some extra code that does something more clever, like change the
post’s formatting based on one of the post details. Examples include making the
post look different based on its category, author, or publication date. The latter is
what this example does.

The final step is to add the code that checks the post’s date and decides whether or
not to highlight it. Here it is, inside the loop you saw earlier. The new code is boldfaced:

<?php while ( have_posts() ) : the_post(); ?>
$postdate = get_the_date(‘Y-m-d’);
$currentdate =
if ($postdate == $currentdate) {
echo ‘<div class=”newpost”>’;
} else {
echo ‘<div>’;
<?php get_template_part( ‘content’, get_post_format() ); ?>
<?php endwhile; ?>


To understand what’s taking place, you need to examine the code one line at a time.
First, it uses a WordPress function named get_the_date(), which returns the date
the current post was published.

$postdate = get_the_time(‘Y-m-d’);

WordPress takes the result from get_the_date() and puts it into a variable (a storage
slot in memory) named $postdate. That way, the code can use the date stored
there at a later time, when the function compares dates.

NOTE It doesn’t matter what you call your variables, as long as you’re consistent. (So you can’t call the
variable $postdate in one place and $date_of_post in another, because you’ll end up creating two separate
variables.) However, your variable names must start with the dollar sign ($), which has the side effect of making
them easily recognizable.

The next line of code creates a second variable, named $currentdate. It stores the
current date, as retrieved by the PHP date() function, which you saw earlier (page
494). Only now the date is returned in a slightly different format, so it matches up
with the publication date format WordPress uses with posts.

$currentdate = date(‘Y-m-d’);

The moment of drama occurs next. An if statement compares the two variables (in
this case, the two dates) to see if the current date matches the publication date (in
other words, to see if the post was published today). If the answer is yes, then the
code adds a new <div> element, with the class name newpost.

if ($postdate == $currentdate) {
echo ‘<div class=”newpost”>’;
If the answer is no, then the code adds a <div> that doesn’t use any class name.
} else {
echo ‘<div>’;

Either way, the code tacks on the closing </div> element at the end of this block of
content, after it inserts the post content into the page.

<?php get_template_part( ‘content’, get_post_format() ); ?>

NOTE This code may seem slightly magical, because it relies on a tight combination of PHP commands
and WordPress functions that you haven’t seen before. Obviously, you wouldn’t be able to cook up this sort of
code on your own. However, you will be able to grab this sort of code from one of the many WordPress recipe
(page 503), and insert it into your templates when you need it. And the more you do that, the easier it’ll
be to recognize the code you want to change, and the more comfortable you’ll be adjusting that code to solve a

Right now, the revised template doesn’t have much of an effect. All it does is add a
<div> element around the post content. However, this <div> gives you a new way to
apply a customized style. You do that by creating a style rule for the newpost class.
Here are the style rules that create the effect shown in Figure 13-17. The first rule
adds the border, spacing, and background color around the post. The second rule
targets the link in the heading, which holds the post title, and gives it large red text.

.newpost {
padding: 8px;
border: 2px solid darkgray;
border-radius: 10px;
background-color: lightyellow;
margin-bottom: 50px;
.newpost h1 a {
font-size: 2.5em;
color: red;

This two-part approach—using the PHP code to add a style, and then defining the
style—is a common technique in theme customization. It gives you the most flexibility,
because you can change the formatting anytime, without editing the template
and wading through the PHP again.

Delving into the Loop

Updating a Child Theme

What happens when I update a theme that uses customized
Child templates don’t work in exactly the same as child styles.
Child styles extend style rules already put in place by the parent
theme. Even if the parent gets a new, updated style.css file,
the child styles remain, and WordPress applies them on top
of the parent styles.
But page templates don’t extend parent templates, they replace
them. As soon as you add footer.php to your child theme,
WordPress starts ignoring the footer.php in the original theme.
That means that if you update the parent theme and change
the original footer.php file, no one really notices.
This is probably the safest way to handle theme updates,
because there really isn’t a way that WordPress could combine
two versions of a template. However, it means that if you
plan to customize all the templates in a theme, you probably
shouldn’t create a child theme. Instead, you may as well build
a completely separate theme of your own.

Updating a Child Theme

Introducing the Template Files

Every theme uses a slightly different assortment of templates. The WordPress staple
Twenty Twelve uses a fairly typical set of about 30 templates.
You can recognize a template by the fact that its filename ends with .php. Although
template files hold a mix of HTML and PHP, the .php extension tells WordPress that
there’s code inside that the WordPress engine needs to run before it sends the final
page to a browser.
Even though a template is just a mix of HTML and PHP, understanding where it fits
into your site can be a bit of a challenge. That’s because every page WordPress
stitches together uses several template files.
For example, imagine you click through to a single post. WordPress has a template,
called single.php, that creates the page on the fly. However, single.php needs help
from a host of other templates. First, it inserts the contents of the header.php
template, which sits at the top of every page in a WordPress site. The header.php
file takes care of basics, like linking to the style sheet, registering some scripts,
and showing the header section, complete with the top-level menu. (Some themes
farm out the menu-creation work to yet another template file, but Twenty Twelve
doesn’t go that far.)
Next, the single.php file adds the Previous and Next navigation links to the post,
and then calls out to another template to display the actual post. If it’s a regular
post, it uses content.php, but the Twenty Twelve theme has a number of specialized
alternatives for different post formats. For example, an “aside” post (page 203) uses
the content-aside.php template, a “status” post uses content-status.php, and so on.
Finally, the single.php template ends by calling three more templates into action. The
comments.php template creates the comments section, the sidebar.php template
adds the widgets on the right, and the footer.php template ends the page.
If you’re going cross-eyed trying to follow this template assortment, Figure 13-14
shows how it all breaks down.
At first glance, this system seems just a bit bonkers. How better to complicate life
than to split the code for a single page into a handful of template files that need to
work together? But in typical WordPress fashion, the design is actually pretty brilliant.
It means that a theme designer can create a single template file that governs
a repeating site element—like a header—and use it everywhere, without needing to
worry about duplicating effort or being inconsistent.

When you edit theme styles, your first challenge is finding the right style rule to
. When you edit templates, the first challenge is finding the right template
file to modify
. Table  can help you get started. It describes the fundamental
templates that almost every theme, including Twenty Twelve, uses.

Keep in mind, however, that themes commonly add extra templates to create the
formats for different types of posts and pages, and to handle special formatting (for
example, to create different layouts that move the sidebar around). You may also
decide to add extra templates of your own (for example, to change the way your
site presents specific categories or authors.




This is a theme’s main template, and the only one
that’s absolutely required. WordPress uses it if
there’s no other, more specific template to use.
Most themes use index.php to display a list of
posts on the home page.


Displays the banner that appears across the
top of every page. Often, header.php includes a
navigation menu.


Displays the footer that stretches across the
bottom of every page.


Shows the sidebar widget area. Twenty Twelve
also has a more specialized sidebar-front.php
template that creates the footer area for pages
that use the Front Page template.

single.php Displays a single post.

Shows a static page. Themes often have additional
page templates that let you create different
“flavors” of pages (page 233). For example,
Twenty Twelve adds a full-width.php template
that creates a page that doesn’t include a sidebar
and a front-page.php template that includes a
two-column widget area in the footer.


Displays the content of a post or page. Some
themes create many different content templates,
for different types of posts and pages. Twenty
Twelve, for instance, has eight content templates.
An ordinary post uses content.php, a page uses
content-page.php, and special post formats
(page 202) use a corresponding template (for
example, asides use content-aside.php).


Displays the comments section after a post or


Shows the attachment page for images—what
you see when you click a picture in a post, if
you’ve set the Link To setting (page 336) to
Attachment Page.


Lists posts when you browse by author, category,
tag, or date. Or you can use one of the four more
specific templates listed next.


Lists posts when you browse a category. You can
also create templates that target specific categories,
like category-tea.php for a category with
“tea” as its simplified name


Lists posts when you browse by tag. You can also
create templates that target specific tags, like


Lists posts when you browse by author. You can
also create templates that target specific authors,
like author-grabinksy.php.


Lists posts after you execute a search.


Displays an error message when the requested
post or page can’t be found.

Introducing the Template Files

Editing the Code in Your Theme THEME

When you want to customize the appearance of a theme, the first place you should
look is the style.css file. But if you need to make more dramatic changes—for example,
revamp the layout, change the information in the post list, or add new widget
areas—you have to go further. Your next step is to consider the theme’s template files.
A typical theme uses anywhere from a dozen to 50 templates. If you crack one
open, you see a combination of HTML markup and PHP code. The PHP code is the
magic ingredient—it triggers the specific WordPress actions that pull your content
out of the database. Before WordPress sends a page to a visitor, it runs all the PHP
code inside it.
Writing this code is a task that’s well beyond the average WordPress website owner.
But that’s not a problem, because you don’t need to write the code yourself, even
if you’re building a completely new theme. Instead, you take a ready-made page
template that contains all the basic code and edit that file to your liking. Here are
two ways you can do that:
• Change the HTML markup. Maybe you don’t need to change the code in the
template file at all. You might just need to modify the HTML that wraps around
it. After all, it’s the HTML (in conjunction with the style sheet) that determines
how your content looks and where it appears.
• Modify the PHP code. You start with a template full of working code. Often, you
can carefully modify this code, using the WordPress documentation, to change
the way it works. For example, imagine you want the list of posts on the home
page to show fewer posts, include just post titles or images instead of content,
or show posts from a specific category. You can do all this by adjusting the code
that’s already in the home page template.
Of course, the more thoroughly you want to edit the PHP, the more you need to learn.
Eventually, you might pick up enough skills to be an accomplished PHP tweaker.


Learning PHP

The actual syntax of the PHP language is beyond the scope of
this book. If you want to develop ninja programming skills,
there are plenty of great resources for learning PHP, whether
you have a programming background or are just starting out.
Don’t rush off just yet, however, because while learning PHP
will definitely help you customize a WordPress theme, it may
not help you as much as you expect.
Learning to customize a WordPress template is partially about
learning PHP (because it helps to understand basic language
details like loops, conditional logic, and functions). But it’s
mostly about learning to use WordPress’s functions in PHP
code (see the Note on page 493 for more about WordPress
functions). For that reason, you’ll probably get more practical
value out of studying WordPress functions than learning the
entire language, unless you plan to someday write dynamic
web pages of your own.
To get started with WordPress functions, check out the function
reference at To learn more about
PHP, start with the absolute basics with the tutorial at http://

Editing the Code in Your Theme THEME