[wp-hackers] Loop Within A Loop

Mike Schinkel mikeschinkel at newclarity.net
Tue Jul 20 20:29:58 UTC 2010


> I am having a problem where I need to call a loop within a loop.

The loop calls setup_postdata() to set $post and other global variables and I think that's where you have some problems.  One related area where I've run into trouble is the need to call "get_the_content()" and use a specified post instead of the global one. Here is the code I use to do that (it's hackishly ugly, but it's because that's what I think I have to do to get around the limitations inherent in WordPress):

		function get_post_content($this_post=false) {
			if ($this_post) {
				global $post, $id, $authordata, $day, $currentmonth, $page, $pages, $multipage, $more, $numpages;
				$save = array($post, $id, $authordata, $day, $currentmonth, $page, $pages, $multipage, $more, $numpages);
				setup_postdata($this_post);
			}
			$content = get_the_content();
			if ($this_post)
				list($post, $id, $authordata, $day, $currentmonth, $page, $pages, $multipage, $more, $numpages) = $save;
			return $content;
		}

You could also create some "get/set" functions to make this more usable in your nested loops, for example (I'd love to see these two functions added to WordPress core, actually):

		function get_postdata($new_post=false) {
			global $post, $id, $authordata, $day, $currentmonth, $page, $pages, $multipage, $more, $numpages;
			$postdata = array($post, $id, $authordata, $day, $currentmonth, $page, $pages, $multipage, $more, $numpages);
			if ($new_post) 
				setup_postdata($new_post);
			return $postdata;
		}
		static function set_postdata($postdata) {
			global $post, $id, $authordata, $day, $currentmonth, $page, $pages, $multipage, $more, $numpages;
			list($post, $id, $authordata, $day, $currentmonth, $page, $pages, $multipage, $more, $numpages) = $postdata;
		}

Of course I could be doing this all wrong and if so I'd love for someone to tell me how I can do this better so it doesn't have to be so hackish.

-Mike


More information about the wp-hackers mailing list