Custom Fields
Re-Envisioned
Support Meta Box AIO Use User Profile Data as Default Data for Other MB Custom Fields

  • Creator
    Topic
  • #32896

    I have custom fields added to the User's profile with Metabox. I'd like to create a new set of custom fields for a CPT, and have the default data for those mapped back to the fields in the user's profile. How can I accomplish this?

    User's Profile:

    Favorite Number = 5

    CPT:

    Favorite Number (Default Data) = [data from user profile favorite number]

    This will allow their "default data" pulled from their profile to be the starting point or default for a field, yet still be editable via the CPT (without overriding the true default stored in their user profile).

Viewing 1 replies (of 1 total)
  • Author
    Replies
  • #32905
    Long Nguyen
    Moderator

    Hi,

    If you have the field number for the user and it has the ID fav_number, then you can use this code to get the user meta and set it as the default value when registering the field number for the post.

    add_filter( 'rwmb_meta_boxes', 'your_prefix_function_name' );
    function your_prefix_function_name( $meta_boxes ) {
        $current_user_id = get_current_user_id();
        $default_number = get_user_meta( $current_user_id, 'fav_number', true );
    
        $meta_boxes[] = [
            'title'  => __( 'Post Meta', 'your-text-domain' ),
            'id'     => 'post-meta',
            'fields' => [
                [
                    'name'       => __( 'Number', 'your-text-domain' ),
                    'id'         => 'number',
                    'type'       => 'number',
                    'std'        => $default_number
                ],
            ],
        ];
        return $meta_boxes;
    }

    Refer to the documentation
    https://developer.wordpress.org/reference/functions/get_user_meta/
    https://docs.metabox.io/field-settings/#default-value

Viewing 1 replies (of 1 total)
  • You must be logged in to reply to this topic.