Custom Fields
Re-Envisioned
Support MB User Meta Pre-selecting terms in an taxonomy-advanced field

This topic contains 2 replies, has 2 voices, and was last updated by  Ryan Lauritsen 6 months, 2 weeks ago.

  • Creator
    Topic
  • #13638
    Resolved
    Ryan Lauritsen
    Participant

    I have a taxonomy_advanced meta field in a user meta box. The taxonomy is a non-hierarchical custom user taxonomy.

    What I want to do is pre-select the choices/terms in the taxonomy field based on the terms currently assigned to the user that is being edited in WP admin. I’m using the rwmb_field_meta filter and the function below to filter the meta value when the field loads.

    $meta contains a comma-separated list of assigned term IDs as expected. But only the first term in the taxonomy field is pre-selected when the user edit admin screen is loaded.

    What do I have to do differently to pre-select ALL the assigned terms in the taxonomy meta field?

    public function populate_user_tags_meta( $meta, $field, $saved ) {
        if( is_admin() ) {
            // Get the user ID for the currently viewed user profile.
            if( defined('IS_PROFILE_PAGE') && IS_PROFILE_PAGE ) {
                // If is current user's profile (profile.php)
                $user_id = get_current_user_id();
            } elseif( !empty($_GET['user_id']) && is_numeric($_GET['user_id']) ) {
                // If is another user's profile page
                $user_id = $_GET['user_id'];
            } else {
                // Otherwise something is wrong.
                die( 'No user ID defined.' );
            }
            // Get the user tags currently assigned to this user.
            $current_users_tags = wp_get_object_terms( $user_id, 'wv_user_tag', array('fields' => 'ids') );
            // Populate meta value with comma-separated string of currently assigned user tag IDs.
            if( !empty($current_users_tags) && !is_wp_error($current_users_tags) ) {
                $meta = implode( ',', array_filter( array_unique( (array) $current_users_tags ) ) );
            } else {
                $meta = '';
            }
        }
        return $meta;
    }
Viewing 2 replies - 1 through 2 (of 2 total)
  • Author
    Replies
  • #13652

    Anh Tran
    Keymaster

    Hi Ryan,

    I’ve tested your code and found that the $meta needs to be an array. So you just need to change the line to:

    $meta = array_filter( array_unique( (array) $current_users_tags ) );

    I also created a video to demo that: http://recordit.co/AcdsXqaeIM. Please take a look.

    #13685

    Ryan Lauritsen
    Participant

    That was it! Works perfectly now. Thank you!

Viewing 2 replies - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.