[wp-hackers] Loops and Cloning

Jess Planck jess at funroe.net
Fri Oct 31 21:27:34 GMT 2008

I'm sharing because I totally ripped this off from drupal and I feel  
guilty for it :)

The problem I had was a multiple loop in a template for a theme that  
displayed posts by a custom field category. Everything worked fine but  
I forgot that I not only have to clone or duplicate the orginal $post,  
but also the $wp_query. I only noticed it because the page menus with  
wp_list_pages lost the current_page CSS classes. Buried in  
wp_list_pages is a global $wp_query.

Moving the original code from an old php4 box to a php5 box really  
hated me. So I dug around and found a nice compatibility wrapper  
function for cloning and duplication of objects from drupal. Don't  
feed it anything but an "object" though...

Happy Halloween!

-- Helper function to clone objects for php4 and php5

function wp_clone($object) {
   return version_compare(phpversion(), '5.0') < 0 ? $object :  

--- A snip of theme template code --

if ( ( $page_category_name =  
get_post_custom_values( 'page_category' ) ) ) {
	// duplicate post and wp_query for later recovery	
	$temp_wp_query = wp_clone( $wp_query );
	$temp_post = wp_clone( $post );

	// set $more to 0 for more links
	global $more;
	$more = 0;
	query_posts( 'category_name=' . $page_category_name[0] .  
'&showposts=' . get_option('posts_per_page') );

do loop stuff...

	// recover post and wp_query
	$post = wp_clone( $temp_post );
	$wp_query = wp_clone( $temp_wp_query );

} // end if ( ( $page_category_option =  
get_post_custom_values( 'page_category' ) ) )

[  :P  ]  jess planck  -  http://funroe.net

More information about the wp-hackers mailing list