0

我有一个带有 2 个元框的 CPT。1 = mv_facility_code2 =mv_facility_email

所有用户都有 dB 列user_facilityuser_facility_email

当站点管理员进入 CPT 并更改时,mv_facility_email我试图找到user_facility值匹配的所有用户mv_facility_code并将其元数据从值更改user_facility_email为新的mv_facility_email.

这是我正在尝试的,但它不起作用。

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 );
        }
    };
};

一如既往,非常感谢任何帮助理解我的错误。

4

1 回答 1

0

您的代码存在一些问题。检查并阅读所有评论

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 );
    }
};
};
于 2020-04-08T05:26:52.803 回答