I have two post types (products and coaches). The products post type has a ‘product-type’ taxonomy with two term (assessments and coaching-packages). When editing a coach, I wanted two Post Type Connection boxes to appear – one for each taxonomy. It would be properly labeled and only show products with that term.
<?php | |
/** | |
* Connect Products and Coaches | |
* | |
*/ | |
function be_p2p_connections() { | |
p2p_register_connection_type( array( | |
'name' => 'coach_assessments', | |
'from' => 'dietitians', | |
'to' => 'product', | |
'title' => array( | |
'to' => 'Connected Coaches', | |
'from' => 'Connected Assessments', | |
) | |
) ); | |
p2p_register_connection_type( array( | |
'name' => 'coach_packages', | |
'from' => 'dietitians', | |
'to' => 'product', | |
'title' => array( | |
'to' => 'Connected Coaches', | |
'from' => 'Connected Coaching Packages', | |
) | |
) ); | |
} | |
add_action( 'p2p_init', 'be_p2p_connections' ); | |
/** | |
* Limit display of P2P metaboxes | |
* | |
*/ | |
function be_p2p_limit_admin_box( $show, $ctype, $post ) { | |
$options = array( | |
'coach_assessments' => 'assessments', | |
'coach_packages' => 'coaching-packages', | |
); | |
foreach( $options as $connection_type => $term ) { | |
if( $ctype->name == $connection_type && 'product' == get_post_type( $post ) ) { | |
$terms = get_the_terms( $post->ID, 'product-type' ); | |
if( !empty( $terms ) ) { | |
$terms = wp_list_pluck( $terms, 'slug' ); | |
$show = in_array( $term, $terms ); | |
} else { | |
$show = false; | |
} | |
} | |
} | |
return $show; | |
} | |
add_filter( 'p2p_admin_box_show', 'be_p2p_limit_admin_box', 10, 3 ); | |
/** | |
* Limit which products show up in P2P metabox | |
* | |
*/ | |
function be_p2p_query_args( $args, $ctype, $post_id ) { | |
$options = array( | |
'coach_assessments' => 'assessments', | |
'coach_packages' => 'coaching-packages', | |
); | |
foreach( $options as $connection_type => $term ) { | |
if( $ctype->name == $connection_type && 'dietitians' == get_post_type( $post_id ) ) | |
$args['product-type'] = $term; | |
} | |
return $args; | |
} | |
add_filter( 'p2p_connectable_args', 'be_p2p_query_args', 10, 3 ); |