certainlyakey
1/29/2015 - 6:43 AM

Wordpress - reuse post code in separate file for custom loops

Wordpress - reuse post code in separate file for custom loops

<?php 
//This is the partial containing all of the code inside any loop on the site

//in the beginning of file
global $custom_wp_query;
if ( isset($custom_wp_query) ) {
	$temp_query = $wp_query;
	$wp_query = $custom_wp_query;
}

//...

//if custom loop is shown
//if (custom_is_part_archive('member')) {
//  echo 'This is a custom member loop, not a main query';
//}
  
//in the end of the file
if ( isset($custom_wp_query) ) {
	$wp_query = $temp_query;
}
<?php
//This is the template where custom loop is shown
$events_args = array('post_type' => 'event', 'numberposts' => 5 );
$events_query = new WP_Query( $events_args );
//This line is important
$custom_wp_query = $events_query;

//optional Posts 2 Posts plugin connection
//in order to use it new WP_Query custom loop method should be used, not get_posts
p2p_type( 'posts_to_events' )->each_connected( $events_query, array(), 'news' );

if ( $events_query->have_posts() ) {
	echo '<h1>Events</h1>';
	while ( $events_query->have_posts() ) {
		$events_query->the_post();
		//Starkers theme utility to include an array of partials. May be replaced with vanilla get_template_part
		Starkers_Utilities::get_template_parts( array( 'parts/post' ) );
	}
	wp_reset_postdata();
}
//Check if a custom query of selected post types is in action. $post_types may be an array of post types or a single CPT as string
function custom_is_part_archive($post_types = array()) {
	global $custom_wp_query;

	if ( isset($custom_wp_query) ) {
		if (!isset($post_types) || empty($post_types)) { //if no parameters at all
			return true;
		} else {
			if (!is_array($post_types)) { //if parameter is string
				$post_types_arr[] = $post_types;
			} else {
				$post_types_arr = $post_types;
			}
			global $post;
			foreach ($post_types_arr as $post_type) {
				if ($post->post_type == $post_type) {
					return true;
				}
			}
		}
	} else {
		return;
	}
}

//May be used together with combined archive checks:
function custom_is_memberarchive() {
  return (is_post_type_archive('member') || custom_is_part_archive('member'));
}