Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Check connection with Posts 2 Posts plugin WordPress

Hi, i have the a post type 'city' with a custom taxonomy 'states'. I have another post type called 'office' and i'm using [[LINK href="http://wordpress.org/extend/plugins/posts-to-posts/"]]Posts 2 Posts[[/LINK]] plugin o create connection between 'cities' and 'offices'.


function my_connection_types() {
p2p_register_connection_type( array(
'name' => 'office_to_city',
'from' => 'office',
'to' => 'city',
'cardinality' => 'many-to-one',
'admin_column' => 'any',
'title' => array( 'from' => __( 'City' ),
'can_create_post' => false
)
);
}
add_action( 'p2p_init', 'my_connection_types' );



I need add in the following code, a way to check if the state (taxonomy) have an office.

Remebering: the offices are connected with cities. The cities have a state taxonomy.



$states = get_terms( 'states' );

foreach ($states as $state) {

$args = array(
'post_type'=>'city',
'order' => 'ASC',
'showposts' => -1,
'tax_query' => array(
array(
'taxonomy' => 'states',
'field' => 'id',
'terms' => array( $state->term_id )
)
)
);

$wp_query = new WP_Query($args);

while ($wp_query->have_posts()) : $wp_query->the_post();

....

endwhile;



Thanks!

Answers (1)

2012-10-10

jazbek answers:

In reading your question, the first thing that popped in my head is why not create a hierarchical "location" taxonomy with cites being children of states? I think it would make your queries much easier to create.


Rodrigo F comments:

I would do this way but my client prefers it that way. He considers less complicated.

He thinks it's easier :(


jazbek comments:

A client telling you how to code, that's not cool! Maybe if you explained to him the complications of the wordpress query?

In any event, it's going to add a lot of queries to your page, but try this:


$states = get_terms( 'states' );
foreach ($states as $state) {
$offices = new WP_Query( array(
'post_type' => 'office',
'connected_type' => 'office_to_city',
'connected_to' => 'any',
'connected_query' => array(
'states' => $state->slug,
),
'nopaging' => true
) );
}


Rodrigo F comments:

jazbek , sorry my bad english. I guess I did not explain very well.

I'm needing to check if each state has at least one office.

example:



$states = get_terms( 'states' );

foreach ($states as $state) {

if($state '<em>has office</em>'){

echo $state. 'has at least one office';

} else {

echo $state. 'has no offices';

}

}