AND Queries in Posts 2 Posts

<?php

/**
 * Add custom query var to allow for querying by multiple p2p connections.
 *
 * @param array $public_query_vars Query vars.
 *
 * @return array
 */
function ea_add_p2p_query_var( $public_query_vars ) {
	$public_query_vars[] = 'p2p_operator';
	return $public_query_vars;
}
add_action( 'query_vars', 'ea_add_p2p_query_var' );

/**
 * Custom query params for processing query.
 *
 * @param string   $groupby    Group by string.
 * @param WP_Query $wp_query WP Query.
 */
function ea_p2p_process_groupby( $groupby, &$wp_query ) {
	global $wpdb;

	if( isset( $wp_query->query_vars['p2p_operator'] ) && 'AND' == $wp_query->query_vars['p2p_operator'] ) {
		$groupby .= " HAVING count($wpdb->p2p.p2p_type) = " . count( $wp_query->query_vars['connected_items'] );
	}
	return $groupby;
}
add_filter( 'posts_groupby', 'ea_p2p_process_groupby', 999, 2 );

/**
 * Use Connnected Posts in Queries
 *
 */
function p2p_query( $query ) {
  if( $query->is_main_query() && ! is_admin() && $query->is_post_type_archive( 'blend' ) ) {
    $oils = isset( $_GET['ms_oils'] ) ? array_map( 'intval', ( explode( ',', $_GET['ms_oils'] ) ) ) : false;
    if( $oils ) {
      $query->set( 'connected_type', 'blends_to_essential_oils' );
      $query->set( 'connected_items', $oils );
      $query->set( 'p2p_operator', 'AND' );
    }
  }
}
add_action( 'parse_query', 'ea_p2p_query' );

Bill Erickson

Bill Erickson is a freelance WordPress developer and a contributing developer to the Genesis framework. For the past 14 years he has worked with attorneys, publishers, corporations, and non-profits, building custom websites tailored to their needs and goals.

Ready to upgrade your website?

I build custom WordPress websites that look great and are easy to manage.

Let's Talk