首页 > 解决方案 > 无法将多个值写回 ACF 用户字段(PHP.Wordpress)

问题描述

我的项目是对导师和学员用户进行初步匹配。然后将多个学员添加到导师。

我的导师有一个 ACF current_mentees(用户列表)字段。我可以添加一个用户。但是当我尝试推送/添加另一个时,它不会添加第二个。

// get mentor & new mentee user arrays from the Match Metadata fields
$mentor = get_field('match_mentor', $post_id);
$mentee = get_field('match_mentee', $post_id);

//get ID from mentor array
$match_mentor_id = $mentor['ID'];  
//get ID from mentee array
$match_mentee_id = $mentee['ID'];

//set up the mentor user_post_id
$mentor_post_id = "user_".$match_mentor_id; 

//get mentor curent_users contents
$current_mentees = get_field('current_mentees', $mentor_post_id, false);

// see if the current mentees is null or has a mentee already
if ($current_mentees == ''){

    //write new current mentees back to the Mentor User Meta fields
    update_field('current_mentees' , $match_mentee_id , $mentor_post_id);

       } else {

   //combine old mentee(s) with new mentee
   array_push( $current_mentees , $match_mentee_id);

//write new current mentees back to the Mentor User Meta fields
update_field('current_mentees' , $current_mentees , $mentor_post_id);

match_mentor & match_mentee 和 current_mentees 都是 ACF 字段。我可以通过用户帐户中的下拉菜单手动将(受指导者)用户(单个和多个)添加到 current_mentees。它显示为数组数组。第一个看起来像:a:1:{i:0;s:2:”60”;} //user 60 添加第二个给我:a:2:{i:0;s:2:”60 ″;i:1;s:2:”57″;} //users 60 & 57 这对我来说是有用的。我希望代码也能做到这一点。

但是...使用上面的代码添加一个用户,在 current_mentees 字段/DB 中我看到 60。然后添加第二个,我得到 a:1:{i:0;i:57;}。(它取代了第一个用户而不是添加第二个用户)。

我不确定这是否开始错误(对于第一个用户),或者我是否需要在添加第二个(我已经尝试过)之前的某个时候更改我的变量。谢谢!

标签: phpwordpressadvanced-custom-fields

解决方案


好的,我今天早上想了几个想法,然后事情就凑齐了。让我发布我修改后的代码。从本质上讲,我尝试遵循自然格式,看看是否可以让所有内容都更进一步。我决定将初始变量转换为数组,这就是让其他一切都符合要求的原因。

// get mentor & new mentee user arrays from the Match Metadata fields
$mentor = get_field(‘match_mentor’, $post_id);
$mentee = get_field(‘match_mentee’, $post_id);

//get ID from mentor array
$match_mentor_id = $mentor[‘ID’];

//get ID from mentee array
$match_mentee_id = $mentee[‘ID’];

//set up the mentor user_post_id
$mentor_post_id = “user_”.$match_mentor_id;

//get user array from mentor curent_users
$current_mentees = get_field(‘current_mentees’, $mentor_post_id, false);

// see if the current mentees is null or has a mentee already
if ($current_mentees == ”) {
    //put data in proper format
    $current_mentees = array();
}

//combine old mentee(s) with new mentee
array_push( $current_mentees , $match_mentee_id);

//write new current mentees back to the Mentor User Meta fields
update_field(‘current_mentees’ , $current_mentees , $mentor_post_id);

推荐阅读