【问题标题】:WP - change usermeta value with metabox value via save_post hookWP - 通过 save_post 钩子用 metabox 值更改 usermeta 值
【发布时间】:2020-04-07 21:37:30
【问题描述】:

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

所有用户都有 dB 列 user_facilityuser_facility_email

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

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

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

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

【问题讨论】:

    标签: php wordpress action-hook


    【解决方案1】:

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

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

    【讨论】:

    • 感谢Shalior,我在抽象代码时忘记传递$args,但它已在实时版本中完成。 $facility_email 是更新后的数据,我已经通过在我的数据库中搜索新值来确认它并显示在 postmeta 中 - 但仍然没有更改 usermeta。
    • 也许foreach 循环中的$user->user_id 没有正确返回用户ID?这是我唯一能想到的。
    • ywc,那是真的,循环中的 $user 是一个 WP_User 对象,id 成员只是 ID,它的 user_id 在您的代码中返回 null。在我的回答中改变了这一点。
    • 检查这个答案,在 wordpress 中调试时记录真的很有帮助:wordpress.stackexchange.com/questions/260236/…
    • 我还根据developer.wordpress.org/reference/hooks/…修改了钩子函数
    猜你喜欢
    • 2017-04-20
    • 2018-02-09
    • 1970-01-01
    • 2014-02-02
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多