How to sync tags between posts that are linked through Posts 2 Posts?

I am faced with a thorny problem and can’t seem to find the solution in the wealth of community knowledge on the web. I have two custom posts types “Person” and “Activities”. I use posts 2 posts (plugin) to link Persons with their various Activities and vice-versa.

I have Taxonomies which apply to Activities. They describe areas of practice and interest. Using them, I’d like to be able to get a list of Persons who partake in Activities tagged with “Cranes”, for example. Where “Cranes” is part of an Area of interest in my tag-like custom taxonomy.

Read More

I suspect the most practical way to go about it would be to apply the taxonomy to both post-types and keep them in sync from the linked Activities to the Persons automatically. Is there a way to do that?

Kind regards,
Evren

EDIT: My p2p_register_connection_type is as follows

function ghunige_connection_types() {
    p2p_register_connection_type( array(
        'name' => 'profile_to_activity',
        'from' => 'ghunige_profile',
        'to' => 'ghunige_activity',
        'reciprocal' => true,
        'title' => array( 'from' => __('Participates in', 'ghunige_dir_domain'), 'to' => __('Participants', 'ghunige_dir_domain') )

    ) );
}

Related posts

1 comment

  1. I think there are 2 solutions for you problem. The first is rely on P2P functions like each_connected (see this as example) and retrieve the connected ‘Person’ after running a taxonomy query for ‘Activities’.

    Maybe this solution can be easier, faster and straightforward.

    Second solution is what you says in your question: apply the taxonomy to both post types.

    To sync taxonomy terms you can hook into action ‘added_term_relationship’ action

       add_action( 'added_term_relationship', 'sync_my_tax', 20, 2);
    
       function sync_my_tax ( $object_id, $tt_id ) { 
         $post = get_post($object_id);
         if ( $post->post_type == 'activities' ) {
           global $wpdb;
           $taxonomy = $wpdb->get_var("SELECT taxonomy FROM $wpdb->term_taxonomy WHERE term_taxonomy_id = " . $tt_id);
           if ( $taxonomy != 'your_taxonomy' ) return; // put here your tax name
           $related = p2p_type( 'person_to_activities' )->get_related( $post );  
           if ( ! empty($related) ) { foreach ( $related as $person ) {
             $wpdb->insert( $wpdb->term_relationships, array( 'object_id' => $person->ID, 'term_taxonomy_id' => $tt_id ) );
           } }
         }
       }
    

    I cannot assure p2p_type call in this code is right because you don’t post your p2p_register_connection_type() call.

    Also note, that all the code is untested, so don’t use on production site before you have fully tested it.

Comments are closed.