Here is an example of code you would place in functions.php
to accomplish this with the Posts 2 Posts plugin:
// Create business/employee relationship
add_action( 'p2p_init', 'register_p2p_connections' );
function register_p2p_connections(){
p2p_register_connection_type(
array(
'name' => 'business_to_employee',
'from' => 'business',
'to' => 'employee',
'title' => array(
'from' => 'Employees',
'to' => 'Employer'
),
'admin_column' => 'to',
'admin_dropdown' => 'to',
'fields' => array(
'title' => array(
'title' => 'Position',
'default' => ''
))));
}
// Auto-publish posts created via P2P box are drafts (they default as drafts).
add_filter( 'p2p_new_post_args', 'p2p_published_by_default', 10, 2 );
function p2p_published_by_default( $args, $ctype ) {
$args['post_status'] = 'publish';
return $args;
}
To list the employees when viewing a business post, in the single-business.php
template, you add some code like this:
// Find connected employee
$connected = new WP_Query( array(
'connected_type' => 'business_to_employee',
'connected_items' => get_queried_object(),
'nopaging' => true,
) );
// Display connected employees
if ( $connected->have_posts() ) : ?>
<h3>Employees:</h3>
<ul>
<?php while ( $connected->have_posts() ) : $connected->the_post(); ?>
<li><?php
the_title();
$position = p2p_get_meta( $post->p2p_id, 'position', true );
echo ( empty($position) ? '' : ", $position" );
?></li>
<?php endwhile; ?>
</ul><?php
endif;
// Restore original (business) post data
wp_reset_postdata();