Automating Meta Box Relationship Creation Between Users and Custom Post Types

Support MB Relationships Automating Meta Box Relationship Creation Between Users and Custom Post Types

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #44477
    Gerhard ReusGerhard Reus
    Participant

    I am trying to automatically assigning add and assign 'Team Member' CPT posts to newly registered users within a WordPress site. I used the user_register action hook to create a 'Team Member' custom post type (CPT) entry that corresponds with each new user, followed by establishing a Meta Box-defined relationship between the user and their 'Team Member' profile. However, the relationship between the newly created 'Team Member' CPT and the user fails to materialize. This issue persists even though the CPT entries are successfully generated. Here is the code I am using:

    add_action('user_register', 'create_team_member_profile');
    
    function create_team_member_profile($user_id) {
        $user_info = get_userdata($user_id);
        $name = $user_info->first_name . ' ' . $user_info->last_name; // For the post title
    
        // Create post object for the team member
        $team_member = array(
            'post_title'  => $name,
            'post_status' => 'publish',
            'post_author' => $user_id,
            'post_type'   => 'team', // Adjust to your CPT slug
        );
    
        // Insert the post into the database and save the post ID
        $post_id = wp_insert_post($team_member);
    
        // Check if Meta Box Relationships API is available and establish the relationship
        if ( function_exists('MB_Relationships_API') ) {
            // Correctly use the API to add the relationship from 'Team' post to 'User'
            MB_Relationships_API::add( $post_id, $user_id, 'team-member-user' );
        }
    }
    #44483
    PeterPeter
    Moderator

    Hello Gerhard,

    You can try to pass a specific post ID and user ID to the MB Relationship API and see if it works:

    function create_team_member_profile($user_id) {
        ...
        // Check if Meta Box Relationships API is available and establish the relationship
        if ( function_exists('MB_Relationships_API') ) {
            // Correctly use the API to add the relationship from 'Team' post to 'User'
            MB_Relationships_API::add( 123, 456, 'team-member-user' );
        }
    }

    If not, I think the callback function is executed before Meta Box and MB extensions are initialized or the relationship ID isn't correct.

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.