How to pre-populate MB relationship field from URL for add new post

Support MB Relationships How to pre-populate MB relationship field from URL for add new post

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #44386
    phillcoxonphillcoxon
    Participant

    Hi have "tramp" and "tramp-contact" custom post types with a MB relationship (Relationship ID: tramp-contact-to-tramp). On the front end I need to provide a link for editors/admins to click to add a new tramp contact and would like to pre-populate the related tramp in the "Add New Tramp Contact" admin screen using a tramp_id URL parameter.

    I'm already doing this with other Metabox custom fields without an issue, but I'm unsure how to target the MB relationship field so that it is pre-populated in the Add New Tramp Contact screen.

    I'd like to do something like the code below, but unsure what id the relationship field has.

    
    function preload_tramp_relationship_from_url_on_create_new_contact() {
        global $pagenow;
    
        // Check if the current page is the "add new post" page for the "tramp-contact" custom post type
        if ($pagenow === 'post-new.php' && isset($_GET['post_type']) && $_GET['post_type'] === 'tramp-contact') {
    
    			/* see https://docs.metabox.io/filters/rwmb-field-meta/ */
     	
                add_filter( 'rwmb_tramp-contact-to-tramp_field_meta', function ( $value, $field, $saved ) 
            {
                $value = isset( $_GET['tramp_id'] ) ? $_GET['tramp_id'] : $value;
    			
                return array($value, $field);
                }, 10, 3);
    
            }
    }
    add_action('admin_init', 'preload_tramp_relationship_from_url_on_create_new_contact');
    

    I've tried both variations:

    rwmb_{$field_type}_field_meta: apply to fields with a specific type
    rwmb_{$field_id}_field_meta: apply to a field with a specific id

    Screenshot of Add New Tramp Contact page with the relationship field I want to pre-populate:

    https://share.zight.com/4guWyGXK

    #44391
    PeterPeter
    Moderator

    Hello,

    Because the relationship field is not a standard custom field so the filter hook rwmb_{$field_id}_field_meta does work with relationship.
    I've already shared a workaround for your case by using JavaScript code https://support.metabox.io/topic/how-can-i-pre-populate-fields-in-new-frontend-submission/

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