<?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; loop</title>
	<atom:link href="http://digwp.com/tag/loop/feed/" rel="self" type="application/rss+xml" />
	<link>http://digwp.com</link>
	<description>Take your WordPress skills to the next level.</description>
	<lastBuildDate>Fri, 18 May 2012 18:21:22 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<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>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>Thumbnail Based Archives</title>
		<link>http://digwp.com/2010/07/thumbnail-based-archives/</link>
		<comments>http://digwp.com/2010/07/thumbnail-based-archives/#comments</comments>
		<pubDate>Mon, 26 Jul 2010 13:36:44 +0000</pubDate>
		<dc:creator>Chris Coyier</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[archives]]></category>
		<category><![CDATA[loop]]></category>

		<guid isPermaLink="false">http://digwp.com/?p=2604</guid>
		<description><![CDATA[Here at Digging Into WordPress, we&#8217;ve attached thumbnail images to every single (non-link-style) post since day one. We started before WordPress 3.0 had the specific feature for thumbnails. We did it just by attaching a file path to the thumbnail image as a custom field. We clearly display each of those thumbnails in the design [...]]]></description>
			<content:encoded><![CDATA[<p>Here at Digging Into WordPress, we&#8217;ve attached thumbnail images to every single (non-link-style) post since day one. We started before WordPress 3.0 had the specific feature for thumbnails. We did it just by attaching a file path to the thumbnail image as a custom field. We clearly display each of those thumbnails in the design of the homepage and other various pages where it makes sense. </p>
<p>The biggest reason we decided to attach post thumbnails from the beginning was that it is just an interesting bit of data to have available for every single post. It means that we could do something like display random thumbnails in the sidebar, or display thumbnails next to search results. We don&#8217;t do either of those things in this current design, but it&#8217;s always a possibility and possibilities are awesome. </p>
<p>Another thing that is a cool thing to build with thumbnails is unique archive views. I&#8217;ve <a href="http://digwp.com/archives/horz/">built one</a> for us here on Digging Into WordPress and I have some ideas for several more. Check it out:</p>
<p><a href="http://digwp.com/archives/horz/"><img src="http://digwp.com/wp-content/uploads/horzarchives.png" alt="" title="horzarchives" width="590" height="253" class="alignright size-full wp-image-2611" /></a></p>
<p>Read on for the &#8220;how&#8221;&#8230;</p>
<p><span id="more-2604"></span></p>
<h3>1. Created a special page template</h3>
<p>This page will be totally unique, no standard header or footer, so I made a template just for it.</p>
<pre><code>&lt;?php
/*
  Template Name: Thumb Archives - Horz
*/
?&gt;</code></pre>
<h3>2. Creating a horizontal row of thumbs</h3>
<p>One of the best ways to create long horizontal row (that breaks the width of the browser window width) is to use a table with a single row of cells. This way we don&#8217;t have to manually set the width of anything, and also don&#8217;t have to worry about things wrapping as we would if the thumbnails were inline elements or floated. </p>
<p>So we&#8217;ll set up a loop querying for every single post on the site (that isn&#8217;t a link-post) and spit out a table cell for each. Within that table cell, there will be an anchor link pointing to the post which contains a title, the image, and an excerpt.</p>
<pre><code>&lt;table id="archives-table"&gt;
	&lt;tr&gt;
		&lt;?php query_posts('posts_per_page=-1&amp;cat=-52'); ?&gt;
		&lt;?php if (have_posts()) : while (have_posts()) : the_post(); ?&gt;
		&lt;td&gt;
			&lt;a href="&lt;?php the_permalink(); ?&gt;" class="article-block"&gt;
				&lt;span class="title"&gt;&lt;?php the_title(); ?&gt;&lt;/span&gt;
				&lt;img src="&lt;?php echo get_post_meta($post-&gt;ID, 'PostThumb', true); ?&gt;" alt="" /&gt;
				&lt;span class="ex"&gt;&lt;?php the_excerpt(); ?&gt;&lt;/span&gt;
			&lt;/a&gt;
		&lt;/td&gt;
		&lt;?php endwhile; endif; ?&gt;
	&lt;/tr&gt;
&lt;/table&gt;</code></pre>
<h3>3. Dependencies</h3>
<p>We&#8217;re going to need a unique CSS file to use for this. Since this template is completely one-off and we aren&#8217;t using the standard header, the &lt;head> element will be right in this template. We&#8217;ll link out to our own custom CSS file, load in jQuery, and load in some plugins that will facilitate the idea I&#8217;m trying to accomplish (<a href="http://www.2meter3.de/code/hoverFlow/">hoverflow</a> and <a href="http://brandonaaron.net/code/mousewheel/docs">mousewheel</a>), as well as finally our own custom JavaScript file.</p>
<pre><code>&lt;head&gt;
  &lt;meta charset="UTF-8" /&gt;
  &lt;title&gt;Thumbnail Archives | Digging Into WordPress&lt;/title&gt;
  &lt;link rel="stylesheet" type="text/css" media="all" href="&lt;?php bloginfo("template_url"); ?&gt;/css/archives-horz.css" /&gt;
  &lt;script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js'&gt;&lt;/script&gt;
  &lt;script src='&lt;?php bloginfo("template_url"); ?&gt;/js/jquery.hoverflow.min.js'&gt;&lt;/script&gt;
  &lt;script src='&lt;?php bloginfo("template_url"); ?&gt;/js/jquery.mousewheel.min.js'&gt;&lt;/script&gt;
  &lt;script src='&lt;?php bloginfo("template_url"); ?&gt;/js/weirdarchives.js'&gt;&lt;/script&gt;
&lt;/head&gt;</code></pre>
<p>If this page was anything more than a one-off page, we should be enqueuing scripts and providing proper hooks in the header and such. I&#8217;ve specifically not done that here because this page is it&#8217;s own unique thing that I don&#8217;t want anything else intruding upon. </p>
<h3>4. Style</h3>
<p>The styling for page is very simple, just a repeating background image and resets. Notice on the page though that the titles and excerpts are hidden until the mouse hovers over the thumbnails. We&#8217;ll do the &#8220;hiding&#8221; by setting the opacity of the thumbnails down to zero in the CSS. We&#8217;ll also position them inset into the thumbnail a bit so they have a bit more dramatic &#8220;reveal&#8221; upon mouse hover, as they slide out and into place.</p>
<pre><code>.title { bottom: 50%; }
.ex { top: 50%; font: 11px Georgia, Serif; color: #555; }
.title, .ex { background: white; width: 130px; padding: 10px; display: block; overflow: hidden; position: absolute; opacity: 0; }
</code></pre>
<h3>5. Horizontal scrolling</h3>
<p>With the mousewheel plugin in place, we can force the window to scroll horizontally instead of vertically with mouse scrollwheels with this:</p>
<pre><code>$("body").mousewheel(function(event, delta) {
    this.scrollLeft -= (delta * 30);
    event.preventDefault();
});</code></pre>
<h3>6. Animation</h3>
<p>When a thumbnail is hovered over, the title and except will show themselves and slide down. To do that, I&#8217;m using jQuery&#8217;s hover function which accepts a function to run on mouseenter and a function to run on mouseleave. For the former, an animation begins which moves the position, height, and opacity. The latter, those values are returned to how they started.</p>
<pre><code>$blocks.hover(function(e) {
    var $el    = $(this),
        $title = $el.find(".title"),
        $ex    = $el.find(".ex");
    
    $title.hoverFlow(e.type, { bottom: "99%", opacity: 1, height: $title.data("origHeight") })
    $ex.hoverFlow(e.type, { top: "95.5%", opacity: 1, height: $ex.data("origHeight") });
    
}, function(e) {
    $(this)
        .find(".title").hoverFlow(e.type, { bottom: "50%", opacity: 0, height: 0 })
        .end()
        .find(".ex").hoverFlow(e.type, { top: "50%", opacity: 0, height: 0 });
});</code></pre>
<p>There is a bit more to the JavaScript (but not much), feel free to poke your way around to it from the demo page to see it all.</p>
<h3>7. More</h3>
<p>The point of all this was to create a unique archive browsing experience based around our thumbnails. This isn&#8217;t the only way to do it. In fact I have a few other ideas I&#8217;m going to work on in time. Are they super practical? Maybe not, but they are fun! </p>
<hr />
<p><small>© 2010 <a href="http://digwp.com">Digging into WordPress</a> | <a href="http://digwp.com/2010/07/thumbnail-based-archives/">Permalink</a> | <a href="http://digwp.com/2010/07/thumbnail-based-archives/#comments">15 comments</a> | Add to <a href="http://del.icio.us/post?url=http://digwp.com/2010/07/thumbnail-based-archives/&title=Thumbnail Based Archives">del.icio.us</a> | Post tags: <a href="http://digwp.com/tag/archives/" rel="tag">archives</a>, <a href="http://digwp.com/tag/loop/" rel="tag">loop</a><br/></small></p>]]></content:encoded>
			<wfw:commentRss>http://digwp.com/2010/07/thumbnail-based-archives/feed/</wfw:commentRss>
		<slash:comments>15</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 Query Shortcode: Run a Loop inside Any Post/Page</title>
		<link>http://digwp.com/2010/01/custom-query-shortcode/</link>
		<comments>http://digwp.com/2010/01/custom-query-shortcode/#comments</comments>
		<pubDate>Thu, 21 Jan 2010 14:43:59 +0000</pubDate>
		<dc:creator>Chris Coyier</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[functions]]></category>
		<category><![CDATA[loop]]></category>
		<category><![CDATA[shortcode]]></category>

		<guid isPermaLink="false">http://digwp.com/?p=1283</guid>
		<description><![CDATA[I had the occasion yesterday to have a page with a section on it where it would output a very specific set of other pages, which would need to change dynamically. What I could have done is built a special page template for this page, and inside that template run a query_posts() to get these [...]]]></description>
			<content:encoded><![CDATA[<p>I had the occasion yesterday to have a page with a section on it where it would output a very specific set of other pages, which would need to change dynamically. What I could have done is built a special page template for this page, and inside that template run a <code>query_posts()</code> to get these posts. But I wanted this page to remain editable from the admin. Besides, creating a special page template every time you need to do something like this is too cumbersome. WordPress is extensible enough to do better. </p>
<p>Hence, the Custom Query Shortcode!</p>
<p><span id="more-1283"></span></p>
<p>This is basically how I wanted it to work. You have a shortcode with one single parameter called &#8220;query&#8221;. (Remember, shortcodes are those things in brackets you can use in the body of Pages/Posts that do special stuff). In the &#8220;query&#8221; parameter, you literally enter exactly what you would enter for a query when using the <code>query_posts()</code> function. In other words:</p>
<pre><code>[loop query=""]</code></pre>
<p>You can pass whatever query you want to it. For example, let&#8217;s say you wanted to query for 20 Pages that were the child of a specific page and list them in Ascending order:</p>
<pre><code>[loop the_query="showposts=20&amp;post_type=page&amp;post_parent=453&amp;ord=ASC"]</code></pre>
<h3>What it returns</h3>
<p>This is totally customizable in the function itself, but I made the judgement call for myself that it would return list items with linked post titles inside. So you&#8217;d go like this:</p>
<pre><code>&lt;ul&gt;
[loop query="posts_per_page=3"]
&lt;/ul&gt;</code></pre>
<p>and you&#8217;d get:</p>
<pre><code>&lt;ul&gt;
&lt;li&gt;&lt;a href="http://digwp.com/post-1/"&gt;Post 1&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://digwp.com/post-2/"&gt;Post 2&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://digwp.com/post-3/"&gt;Post 3&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</code></pre>
<p>And of course those would be real URL&#8217;s and real Post titles&#8230;</p>
<h3>The Code</h3>
<p>This would go in your themes functions.php file. Now that I&#8217;m thinking more clearly about it, this probably makes more sense to be a plugin since it probably shouldn&#8217;t be theme-dependant, but oh well, we can do that another day.</p>
<pre><code>function custom_query_shortcode($atts) {

   // EXAMPLE USAGE:
   // [loop the_query="showposts=100&amp;post_type=page&amp;post_parent=453"]
   
   // Defaults
   extract(shortcode_atts(array(
      "the_query" =&gt; ''
   ), $atts));

   // de-funkify query
   $the_query = preg_replace('~&amp;#x0*([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $the_query);
   $the_query = preg_replace('~&amp;#0*([0-9]+);~e', 'chr(\\1)', $the_query);

   // query is made               
   query_posts($the_query);
   
   // Reset and setup variables
   $output = '';
   $temp_title = '';
   $temp_link = '';
   
   // the loop
   if (have_posts()) : while (have_posts()) : the_post();
   
      $temp_title = get_the_title($post-&gt;ID);
      $temp_link = get_permalink($post-&gt;ID);
      
      // output all findings - CUSTOMIZE TO YOUR LIKING
      $output .= "&lt;li&gt;&lt;a href='$temp_link'&gt;$temp_title&lt;/a&gt;&lt;/li&gt;";
          
   endwhile; else:
   
      $output .= "nothing found.";
      
   endif;
   
   wp_reset_query();
   return $output;
   
}
add_shortcode("loop", "custom_query_shortcode");</code></pre>
<h3>Credit</h3>
<p>When I first wrote this up to use, it totally didn&#8217;t work. I couldn&#8217;t figure it out&#8230; the query was getting passed over just fine, and if I hard coded the query, the whole thing would work just fine. It turns out that because the shortcode lived inside the content of a Post/Page, the ampersand characters in the query were getting encoded, and thus screwing up the query. </p>
<p><a href="http://sketchpad.co.uk/">Dan Smith</a> had the genius idea to use html_entity_decode() on the query before using it in query_posts(), but for some reason I couldn&#8217;t get it to take. </p>
<p><a href="http://www.rogerstringer.com/">Roger Stringer</a> coded up the solution with regular expressions you see above. Thanks guys!</p>
<hr />
<p><small>© 2010 <a href="http://digwp.com">Digging into WordPress</a> | <a href="http://digwp.com/2010/01/custom-query-shortcode/">Permalink</a> | <a href="http://digwp.com/2010/01/custom-query-shortcode/#comments">10 comments</a> | Add to <a href="http://del.icio.us/post?url=http://digwp.com/2010/01/custom-query-shortcode/&title=Custom Query Shortcode: Run a Loop inside Any Post/Page">del.icio.us</a> | Post tags: <a href="http://digwp.com/tag/functions/" rel="tag">functions</a>, <a href="http://digwp.com/tag/loop/" rel="tag">loop</a>, <a href="http://digwp.com/tag/shortcode/" rel="tag">shortcode</a><br/></small></p>]]></content:encoded>
			<wfw:commentRss>http://digwp.com/2010/01/custom-query-shortcode/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Two Ways to Limit the Number of Posts without a Plugin</title>
		<link>http://digwp.com/2009/12/limit-posts-without-plugin/</link>
		<comments>http://digwp.com/2009/12/limit-posts-without-plugin/#comments</comments>
		<pubDate>Thu, 10 Dec 2009 13:27:10 +0000</pubDate>
		<dc:creator>Jeff Starr</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[loop]]></category>
		<category><![CDATA[template]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://digwp.com/?p=1046</guid>
		<description><![CDATA[Let&#8217;s say your blog is set to display ten posts per page, as specified via the WordPress Admin under Settings &#62; Reading. Once set, ten posts will appear on your home page, archive pages, search results, and so on. In other words, if it isn&#8217;t a single-view page or an actual &#8220;page&#8221; page, you&#8217;re gonna [...]]]></description>
			<content:encoded><![CDATA[<p>Let&rsquo;s say your blog is set to display ten posts per page, as specified via the WordPress Admin under <strong>Settings &gt; Reading</strong>. Once set, ten posts will appear on your home page, archive pages, search results, and so on. In other words, if it isn&rsquo;t a single-view page or an actual &ldquo;page&rdquo; page, you&rsquo;re gonna get ten posts per page. It&rsquo;s a <em>global</em> setting.</p>
<p>But what if you want to display different numbers of posts for different types of page views? For example, instead of showing just ten posts on your search-results pages, you may want to show a whole bunch, like maybe fifty or something. Perhaps you would also like to <em>limit</em> the number of posts displayed on your category archives to only five. Of course, many of us know the <em>easy</em> way to do this: install <a href="http://moshublog.com/2007/10/30/custom-query-string-reloaded-for-wordpress-23-with-tag-support/" title="Custom Query String Reloaded">Custom Query String</a> or <a href="http://coffee2code.com/wp-plugins/custom-post-limits/" title="Custom Post Limits">Custom Post Limits</a>, tweak a few settings, and call it good. But.. this <em>does</em> require commitment to yet another plugin, which is a good reason for doing things the &ldquo;hard&rdquo; way..</p>
<p><span id="more-1046"></span></p>
<h3>Method 1</h3>
<p>Fortunately, we can account for the latter scenario <em>without</em> relying on a plugin. Normally, the loop controls the number of posts displayed via the <code>while(have_posts())</code> condition, as shown in this extremely boring example of a typical loop:</p>
<pre><code>&lt;?php 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;p&gt;?php the_time(); ?&gt;&lt;/p&gt;
	&lt;?php the_content(); ?&gt;
	&lt;p&gt;&lt;?php the_tags(); ?&gt;&lt;/p&gt;

&lt;?php endwhile;?&gt;

	&lt;p&gt;&lt;?php next_posts_link(); ?&gt;&lt;/p&gt;
	&lt;p&gt;&lt;?php previous_posts_link(); ?&gt;&lt;/p&gt;

&lt;?php else : ?&gt;

	&lt;h1&gt;Not Found&lt;/h1&gt;
	&lt;p&gt;Silly monkey.&lt;/p&gt;

&lt;?php endif; ?&gt;</code></pre>
<p>What&rsquo;s happening here is that we are running the loop <strong>only&nbsp;if</strong> we <em>have</em> posts, and only <strong>while</strong> the number of posts is <em>less than or equal to</em> the amount specified in the Admin area. Thus, limiting the number of posts is simply a matter of replacing &ldquo;<code>while(have_posts())</code>&rdquo; with something more restrictive.</p>
<p>There are probably a zillion ways of doing this, but the easiest that I have found is to simply setup a counter variable to keep track of each iteration of the loop. Once the counter variable reaches the specified value, the loop stops. Here&rsquo;s the previous example loop showing the required modifications:</p>
<pre><code>&lt;?php $i = 1; while (have_posts() &amp;&amp; $i &lt; 6) : 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;p&gt;?php the_time(); ?&gt;&lt;/p&gt;
	&lt;?php the_content(); ?&gt;
	&lt;p&gt;&lt;?php the_tags(); ?&gt;&lt;/p&gt;

&lt;?php $i++; endwhile; ?&gt;

	&lt;p&gt;&lt;?php next_posts_link(); ?&gt;&lt;/p&gt;
	&lt;p&gt;&lt;?php previous_posts_link(); ?&gt;&lt;/p&gt;

&lt;?php else : ?&gt;

	&lt;h1&gt;Not Found&lt;/h1&gt;
	&lt;p&gt;Silly monkey.&lt;/p&gt;

&lt;?php endif; ?&gt;</code></pre>
<p>Notice that in the first line we are initiating the counter variable &ldquo;<code>$i</code>&rdquo; and then setting its limit at &ldquo;<code>6</code>&rdquo;. We also add &ldquo;<code>$i++;</code>&rdquo; before the &ldquo;<code>endwhile</code>&rdquo; statement to increase the count by one for each iteration of the loop. The result of these modifications is that the loop will now run only five times (as specified in the first line) instead of ten times (as specified in the WordPress Admin).</p>
<p>Just keep in mind that this trick only works when you want to <em>limit</em> the total number of posts displayed on a particular page. Even so, it is still possible to avoid a plugin by setting your default post display to something high, like 20 or 30. Then, your blog displays the highest number of posts where you want them, and everything less is customized by limiting this default number with a couple lines of code. This technique could also be useful for designing themes that required a specific number of posts displayed in certain areas of the blog.</p>
<h3>Method 2</h3>
<p><strong>Or</strong>, you could just use <code>query_posts</code> to create a custom query and specify the <code>showposts</code> parameter with a value of &ldquo;<code>5</code>&rdquo; (or whatever number you wish). Here is what our original loop example looks like using the <code>query_posts</code> function:</p>
<pre><code>&lt;?php query_posts('showposts=5'); 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;p&gt;?php the_time(); ?&gt;&lt;/p&gt;
	&lt;?php the_content(); ?&gt;
	&lt;p&gt;&lt;?php the_tags(); ?&gt;&lt;/p&gt;

&lt;?php endwhile;?&gt;

	&lt;p&gt;&lt;?php next_posts_link(); ?&gt;&lt;/p&gt;
	&lt;p&gt;&lt;?php previous_posts_link(); ?&gt;&lt;/p&gt;

&lt;?php else : ?&gt;

	&lt;h1&gt;Not Found&lt;/h1&gt;
	&lt;p&gt;Silly monkey.&lt;/p&gt;

&lt;?php endif; wp_reset_query(); ?&gt;</code></pre>
<p>Notice the two additions to the original loop: in the first line, we added the <code>query_posts</code> function with the required <code>posts_per_page</code> parameter set to <code>5</code>. Then, in the last line, we invoke the mystical powers of <code>wp_reset_query</code> to reset the original posts query. Resetting the query ensures that it&rsquo;s available elsewhere in the template and is just good practice in general when using <code>query_posts</code>. </p>
<p>The <strong>pros</strong> of using <code>query_posts</code> to modify the number of posts is that you can go either way &#8212; you can either <em>decrease</em> or <em>increase</em> the total number of posts displayed on any page &#8212; no plugins necessary.</p>
<p>The <strong>cons</strong> of using the <code>query_posts</code> method mainly involve the disruption of the original <code>wp_query</code> object normally used to communicate parameters involving page, category, search, and other properties to the <acronym title="Structured Query Language">SQL</acronym> query*. Avoiding this drama is one of the reasons why using a simple counter variable (as described in the first half of the post) is often the preferred method (multiple loops, anyone?).</p>
<p>*<strong>Note:</strong> It <em>is</em> possible to include this default information in the <code>query_posts</code> query, but doing so is a bit beyond the scope of this article.</p>
<hr />
<p><small>© 2009 <a href="http://digwp.com">Digging into WordPress</a> | <a href="http://digwp.com/2009/12/limit-posts-without-plugin/">Permalink</a> | <a href="http://digwp.com/2009/12/limit-posts-without-plugin/#comments">18 comments</a> | Add to <a href="http://del.icio.us/post?url=http://digwp.com/2009/12/limit-posts-without-plugin/&title=Two Ways to Limit the Number of Posts without a Plugin">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/template/" rel="tag">template</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/2009/12/limit-posts-without-plugin/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Easy Custom Feeds in WordPress</title>
		<link>http://digwp.com/2009/09/easy-custom-feeds-in-wordpress/</link>
		<comments>http://digwp.com/2009/09/easy-custom-feeds-in-wordpress/#comments</comments>
		<pubDate>Mon, 14 Sep 2009 05:37:31 +0000</pubDate>
		<dc:creator>Jeff Starr</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Theme]]></category>
		<category><![CDATA[feeds]]></category>
		<category><![CDATA[functions]]></category>
		<category><![CDATA[loop]]></category>
		<category><![CDATA[query_posts]]></category>

		<guid isPermaLink="false">http://digwp.com/?p=552</guid>
		<description><![CDATA[Now that we have seen how to setup Tumblr-style posts, it would be nice to be able to segregate the Tumblr-posts category from the main feed into its own, separate feed. This would enable readers to subscribe exclusively to the Tumblr-posts feed and maybe display it in their sidebar or something. While we&#8217;re at it, [...]]]></description>
			<content:encoded><![CDATA[<p>Now that we have seen how to <a href="http://digwp.com/2009/09/tumblr-style-links-for-posts-and-feeds/" title="How to Implement Tumblr-Style Links for Posts and Feeds">setup Tumblr-style posts</a>, it would be nice to be able to segregate the Tumblr-posts category from the main feed into its own, separate feed. This would enable readers to subscribe exclusively to the Tumblr-posts feed and maybe display it in their sidebar or something. While we&rsquo;re at it, it would also be cool to be able to provide readers with a full menu of feed choices, including the following:</p>
<ul>
<li>&ldquo;Everything&rdquo; feed &#8212; that would include both the main posts and the Tumblr posts</li>
<li>&ldquo;Articles-only&rdquo; feed &#8212; that would include only the main articles and no Tumblr stuff</li>
<li>&ldquo;Tumblr-only&rdquo; feed &#8212; that would include only the Tumblr-style posts</li>
</ul>
<p><span id="more-552"></span></p>
<h3>Overview of this tutorial</h3>
<p>To accomplish our goals, we&rsquo;ll perform the following steps:</p>
<ol>
<li>Create two custom-Page templates</li>
<li>Create two Pages, one for the articles and one for the Tumblr-posts</li>
<li>Assign the custom templates to their respective Pages</li>
<li>Make sure the feeds validate and clean up theme tags</li>
</ol>
<p>That&rsquo;s the plan, now let&rsquo;s <em>dig in</em>!</p>
<h3>Step 1: create a couple custom-page templates</h3>
<p>Our two custom Page-templates will contain all of the code needed to generate our two custom feeds. These two custom templates are almost identical. For the articles-only feed, we will <em>exclude</em> the tumblelog category from the loop, and for the tumblr-only feed, we will <em>include</em> only the tumblelog category. </p>
<p>Let&rsquo;s do the articles-only Page template first. In your theme, create a new Page-template file called &ldquo;articles.php&rdquo; and insert the following code:</p>
<pre><code>&lt;?php 
/* 
Template Name: Articles
*/
$numposts = 10; // number of posts in feed
$posts = query_posts('showposts='.$numposts.'&amp;cat=-1'); // replace the number 1 with the ID of your tumblelog category
$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>Alternately, you may <a href="http://digwp.com/plugins/easy-custom-feeds.zip" title="Download ZIP file">download the two required page-template files here</a>.</p>
<p>Once you have that code in place, edit the <code>$numposts</code> variable according to the number of articles that you would like to display in the articles-only feed. Then edit the <code>$posts</code> variable according to the ID of your tumblelog category. See the comments in the code for details.</p>
<p>That&rsquo;s it for your articles-only feed. Now, for your tumblr-only feed, create another new Page-template file called &ldquo;tumblelog.php&rdquo; and insert the exact same chunk of code as before. The first change that we need to make for this second template is to remove the hyphen (&nbsp;<code>-</code>&nbsp;) from the <code>$numposts</code> variable like so:</p>
<p><code>$posts = query_posts('showposts='.$numposts.'&amp;cat=1');</code></p>
<p>This tells WordPress to include <em>only</em> your tumblelog category in your tumblr-only feed. For your articles-only feed, the <em>presence</em> of the hyphen (negative&nbsp;sign, whatever) tells WordPress to <em>exclude</em> your tumblelog category. Simple, but effective.</p>
<p>The second (and final) change that we need to make for the tumblr-only template is to give it a new template name in the first line:</p>
<p><code>Template Name: Tumblelog</code></p>
<p>This will enable WordPress to distinguish between the two custom templates in the next step.</p>
<h3>Step 2: create two Pages in the WordPress Admin</h3>
<p>With your two custom Page-templates uploaded to your server, login to your Admin area and create two new Pages:</p>
<ul>
<li>Create a Page called &ldquo;Articles&rdquo; and assign it the &ldquo;Articles&rdquo; template</li>
<li>Create a Page called &ldquo;Tumblelog&rdquo; and assign it the &ldquo;Tumblelog&rdquo; template</li>
</ul>
<p>At this point, your two new custom feeds are fully functional, appearing at the following <acronym title="Uniform Resource Locator">URL</acronym>s:</p>
<ul>
<li><code>http://domain.tld/articles/</code> &#8212; articles-only feed</li>
<li><code>http://domain.tld/tumblelog/</code> &#8212; tumblr-only feed</li>
</ul>
<p>Once you have some posts in your tumblr-only category, you will see that they are excluded from the articles-only feed and appear by themselves in the tumblr-only feed. Of course, your main posts feed, located at <code>http://domain.tld/feed/</code> will contain <em>all</em> of your posts, enabling you to offer the following feeds to your readers:</p>
<ul>
<li>&ldquo;Everything&rdquo; feed &#8212; that would include both the main posts and the Tumblr posts</li>
<li>&ldquo;Articles-only&rdquo; feed &#8212; that would include only the main articles and no Tumblr stuff</li>
<li>&ldquo;Tumblr-only&rdquo; feed &#8212; that would include only the Tumblr-style posts</li>
</ul>
<h3>Final step: validation and theme clean-up</h3>
<p>Now that everything is working, you should take the time to double-check the validity of your new feeds. This will ensure that subscribers receive the correct content in the proper format. Rest assured, I have already validated the <acronym title="eXtensible Markup Language">XML</acronym> produced from the custom page-template, but double-checking is always a good idea in case there are any unintended side-effects from plugins, scripts and whatnot.</p>
<p>One of our favorite validation services is available at: <a href="http://beta.feedvalidator.org/" title="feedvalidator.org">http://beta.feedvalidator.org/</a> &#8212; go there and enter the <acronym title="Uniform Resource Locator">URL</acronym>s of your new feeds.</p>
<p>Here at <acronym title="Digging into WordPress">DiW</acronym>, we recently used this exact method to establish an articles-only feed for use at <a href="http://planetwordpress.planetozh.com/" title="Planet WordPress">Planet WordPress</a>. You can see that <a href="http://beta.feedvalidator.org/check.cgi?url=http%3A%2F%2Fdigwp.com%2Farticles%2F" title="Validation of the DiW Articles Feed">it validates quite nicely</a>.</p>
<p>Finally, after setting up your custom feeds, you should go into your theme and add some nice &ldquo;subscribe&rdquo; links for your readers. Also want to remind you that your new feeds are in fact <em>Pages</em>, such that you may want to remove them from any automatic Page-listings generated by the <a href="http://digwp.com/2009/07/delicious-recipes-wordpress-page-menus/" title="Delicious Recipes for WordPress Page Menus and Page Listings"><code>wp_list_pages</code> or <code>wp_page_menu</code> template tags</a>. For example, you can easily exclude your two feed Pages as follows:</p>
<p><code>wp_list_pages('exclude=123,456');</code></p>
<p>Where &ldquo;<code>123</code>&rdquo; and &ldquo;<code>456</code>&rdquo; are the IDs of your Articles and Tumblelog Pages.</p>
<h3>Wrapping it up</h3>
<p>With the technique described in this article, you now have an easy, sure-fire way of creating custom feeds in WordPress. The code for the feed markup is highly versatile, and may be customized to suit virtually any custom-feed configuration.</p>
<hr />
<p><small>© 2009 <a href="http://digwp.com">Digging into WordPress</a> | <a href="http://digwp.com/2009/09/easy-custom-feeds-in-wordpress/">Permalink</a> | <a href="http://digwp.com/2009/09/easy-custom-feeds-in-wordpress/#comments">7 comments</a> | Add to <a href="http://del.icio.us/post?url=http://digwp.com/2009/09/easy-custom-feeds-in-wordpress/&title=Easy Custom Feeds in WordPress">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/loop/" rel="tag">loop</a>, <a href="http://digwp.com/tag/query_posts/" rel="tag">query_posts</a><br/></small></p>]]></content:encoded>
			<wfw:commentRss>http://digwp.com/2009/09/easy-custom-feeds-in-wordpress/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Create a Stunning Lightbox-Style Random-Post Header Gallery</title>
		<link>http://digwp.com/2009/06/random-lightbox-header-gallery/</link>
		<comments>http://digwp.com/2009/06/random-lightbox-header-gallery/#comments</comments>
		<pubDate>Mon, 22 Jun 2009 14:09:43 +0000</pubDate>
		<dc:creator>Jeff Starr</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[custom-fields]]></category>
		<category><![CDATA[header]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[layout]]></category>
		<category><![CDATA[lightbox]]></category>
		<category><![CDATA[loop]]></category>

		<guid isPermaLink="false">http://diggingintowordpress.com/?p=150</guid>
		<description><![CDATA[In this tutorial, we&#8217;re going to take advantage of two of WordPress&#8217; most powerful features, get_posts() and custom fields, to create a stunning random lightbox-style header gallery for your post images. Displayed before the standard post loop, this lightbox gallery will randomly display the images that are associated with your posts while also providing a [...]]]></description>
			<content:encoded><![CDATA[<p>In this tutorial, we&rsquo;re going to take advantage of two of WordPress&rsquo; most powerful features, <code>get_posts()</code> and custom fields, to create a stunning random lightbox-style header gallery for your post images. Displayed <em>before</em> the standard post loop, this lightbox gallery will randomly display the images that are associated with your posts while also providing a descriptive title link to the post itself. Here is a graphical representation that will help us visualize what we are going to do:</p>
<p><img src="http://digwp.com/wp-content/blog-images/lightbox-tutorial.jpg" alt="" title="" /><br /><small>Random post-display functionality with lightbox-style popup image and title post link</small></p>
<p>The key to setting this up involves creating a set of custom fields for each post and then displaying the information randomly before the main post loop. Let&rsquo;s begin with the custom fields.</p>
<p><span id="more-150"></span></p>
<h3>Setting up the custom fields</h3>
<p>If you have already been taking advantage of <a href="http://perishablepress.com/press/2008/12/17/wordpress-custom-fields-tutorial/" title="WordPress Custom Fields, Part I: The Basics">WordPress custom fields</a>, then you already understand the basic idea here. For each post that you would like to have appear randomly in the header of your theme, create the following custom fields:</p>
<p><img src="http://digwp.com/wp-content/blog-images/custom-fields.gif" alt="" title="" /><br /><small>Custom-field data associated with each randomly displayed post</small></p>
<p>Notice that we are using <em>relative</em> file paths for the images. This trick ensures maximum flexibility and portability for our custom-field data. Also note the two different images we are using for each post: a full-size image that will be displayed in the lightbox popup, and a cropped or resized version of that same image for display in the random header.</p>
<p>Once you have associated these custom fields with a few of your posts, it is time for a little <code>get_posts()</code> action to display the random content in your active theme.</p>
<h3>Editing your WordPress theme files</h3>
<p>One of the great things about WordPress custom fields is that they enable you to display your content in just about any way imaginable. In this tutorial, we are going to display our custom-field data in the header area for every page on the site. Thus, we open our theme&rsquo;s <code>header.php</code> file and add the following code:</p>
<pre><code>&lt;?php $random = get_posts('showposts=1&amp;orderby=rand'); foreach($random as $post) : setup_postdata($post); ?&gt;

&lt;p&gt;
	&lt;a href="http://domain.tld&lt;?php echo get_post_meta($post-&gt;ID, 'randomImage', true); ?&gt;" title="&lt;?php echo get_post_meta($post-&gt;ID, 'randomCaption', true); ?&gt;" class="thickbox"&gt;
		&lt;img src="http://domain.tld&lt;?php echo get_post_meta($post-&gt;ID, 'randomBanner', true); ?&gt;" alt="" /&gt;
	&lt;/a&gt;
	&lt;small&gt;&lt;a href="http://domain.tld&lt;?php echo get_post_meta($post-&gt;ID, 'randomLink', true); ?&gt;"&gt;&lt;?php echo get_post_meta($post-&gt;ID, 'randomTitle', true); ?&gt;&lt;/a&gt;&lt;/small&gt;
&lt;/p&gt;

&lt;?php endforeach; ?&gt;</code></pre>
<p>As mentioned, this code goes before the normal WordPress loop and calls data from each of the five custom fields that have been added to your posts. Instead of using the more powerful <code>query_posts()</code> for this random post display, we use the simpler <a href="http://codex.wordpress.org/Template_Tags/get_posts" title="WordPress Codex: Template Tags/get posts">get_posts()</a> function instead. It does everything we need while eliminating unnecessary variables and potential complications.</p>
<p>A few other points of interest for this WordPress snippet; notice we are setting the randomness and limiting the post display to one (&nbsp;<code>1</code>&nbsp;) via two parameters in the <code>get_posts()</code> function. Once the query has been setup, we are using the <a href="http://codex.wordpress.org/Function_Reference/get_post_meta" title="Function Reference/get post meta">get_post_meta()</a> tag to populate the following markup with their respective custom-field values:</p>
<pre><code>&lt;p&gt;
	&lt;a href="[randomImage]" title="[randomCaption]" class="thickbox"&gt;
		&lt;img src="[randomBanner]" alt="" /&gt;
	&lt;/a&gt;
	&lt;small&gt;&lt;a href="[randomLink]"&gt;[randomTitle]&lt;/a&gt;&lt;/small&gt;
&lt;p&gt;</code></pre>
<p>This demonstrates the incredible design flexibility enabled by WordPress custom fields. Once this code is in place, it is time to wrap things up by implementing the JavaScript-powered lightbox functionality.</p>
<h3>Adding the JavaScript</h3>
<p>To finish things off, let&rsquo;s make that random-banner image really &ldquo;pop&rdquo; by implementing some JavaScript-powered lightbox functionality. As you probably know, there are <a href="http://planetozh.com/projects/lightbox-clones/" title="The Lightbox Clones Matrix">many lightbox clones</a> from which to choose, but for this tutorial we turn to Cody Lindley&rsquo;s excellent <a href="http://jquery.com/demo/thickbox/" title="ThickBox 3.1">Thickbox</a> script:</p>
<blockquote><p>ThickBox is a webpage UI dialog widget written in JavaScript on top of the jQuery library. Its function is to show a single image, multiple images, inline content, iframed content, or content served through AJAX in a hybrid modal.</p></blockquote>
<p>Using Thickbox is <em>so</em> easy, it almost feels like I&rsquo;m just being lazy for using it. In fact, we have already setup our WordPress code for use with Thickbox by simply adding the <code>class="thickbox"</code> attribute to the random-banner anchor element. The only other thing that really needs to be done is to upload the Thickbox script and accompanying <acronym title="Cascading Style Sheets">CSS</acronym> file to your server and link to them from the <code>&lt;head&gt;</code> section of your <code>header.php</code> file:</p>
<pre><code>&lt;link rel="stylesheet" href="http://domain.tld/wp-content/css/thickbox.css" type="text/css" media="screen" /&gt;
&lt;script type="text/javascript" src="http://domain.tld/wp-content/javascript/thickbox-compressed.js"&gt;&lt;/script&gt;</code></pre>
<h3>Putting it all together</h3>
<p>Once everything is in place, your random-post gallery should be working great. To see a working example of this technique, check out the header area of <a href="http://eightyeightteeth.com/" title="EightyEightTeeth.com - Graphics Portfolio of Thane Champie">Thane Champie&rsquo;s Graphics Portfolio site</a>. That particular implementation of this method features a few more bells and whistles, but the basic functionality is the same.</p>
<hr />
<p><small>© 2009 <a href="http://digwp.com">Digging into WordPress</a> | <a href="http://digwp.com/2009/06/random-lightbox-header-gallery/">Permalink</a> | <a href="http://digwp.com/2009/06/random-lightbox-header-gallery/#comments">15 comments</a> | Add to <a href="http://del.icio.us/post?url=http://digwp.com/2009/06/random-lightbox-header-gallery/&title=Create a Stunning Lightbox-Style Random-Post Header Gallery">del.icio.us</a> | Post tags: <a href="http://digwp.com/tag/custom-fields/" rel="tag">custom-fields</a>, <a href="http://digwp.com/tag/header/" rel="tag">header</a>, <a href="http://digwp.com/tag/javascript/" rel="tag">JavaScript</a>, <a href="http://digwp.com/tag/layout/" rel="tag">layout</a>, <a href="http://digwp.com/tag/lightbox/" rel="tag">lightbox</a>, <a href="http://digwp.com/tag/loop/" rel="tag">loop</a><br/></small></p>]]></content:encoded>
			<wfw:commentRss>http://digwp.com/2009/06/random-lightbox-header-gallery/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
	</channel>
</rss>

