WP - change usermeta value with metabox value via save_post hook

59 Views Asked by At

I have a CPT with 2 metaboxes. 1 = mv_facility_code 2 = mv_facility_email

All users have dB columns user_facility and user_facility_email

When a site admin goes into the CPT and changes the mv_facility_email I'm trying to find all users who's user_facility value matches mv_facility_code and change their metadata from the value in user_facility_email to the new mv_facility_email.

Here's what I'm trying, but it's not working.

add_action( 'save_post_cpt', 'mv_update_user_facility_details' );
function mv_update_user_facility_details() {

    $facility_code = get_post_meta($post->ID, 'mv_facility_code', true);
    $facility_email = get_post_meta($post->ID, 'mv_facility_email', true);

    $args = array(
        'meta_key' => 'user_facility',
        'meta_value' => $facility_code,
    );

    $user_query = new WP_User_Query();
    $users = $user_query->get_results();

    if ( ! empty( $users ) ) {
        foreach ( $users as $user ) {
            update_user_meta( $user->user_id, 'user_facility_email', $facility_email );
        }
    };
};

Any help understanding my error is, as always, greatly appreciated.

1

There are 1 best solutions below

5
On BEST ANSWER

there are some problems with your code. check this and read all comments

add_action( 'save_post_cpt', 'mv_update_user_facility_details' , 10  ,3 );

/**
 * @param WP_Post $post
 * passing all 3 parameter to function
 */

function mv_update_user_facility_details($post_id , $post, $update) {
if (! $update ) return;
$facility_code = get_post_meta($post_id, 'mv_facility_code', true);
//make sure this is the updated data
$facility_email = get_post_meta($post_id, 'mv_facility_email', true);

//args never used
$args = array(
    'meta_key' => 'user_facility',
    'meta_value' => $facility_code,
);
//pass it to constructor
$user_query = new WP_User_Query($args);
$users = $user_query->get_results();



//i prefer do it like this , same thing just easier to read 
$users = get_users([
    'meta_key' => 'user_facility',
    'meta_value' => $facility_code,
]);

if ( ! empty( $users ) ) {
    foreach ( $users as $user ) {
        update_user_meta( $user->ID, 'user_facility_email', $facility_email );
    }
};
};