Невозможно записать несколько значений обратно в пользовательское поле ACF (PHP. Wordpress) - PullRequest
0 голосов
/ 01 октября 2018

Мой проект состоит в том, чтобы сделать начальный матч наставников и подопечных пользователей.А затем добавьте несколько наставников к наставнику.

У моего наставника есть поле 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.Я могу вручную добавить (mentee) пользователей (одиночных и множественных) в current_mentees через раскрывающийся список в учетной записи пользователя.Появляется как массив массивов.Первый выглядит так: a: 1: {i: 0; s: 2: ”60 ″;} // user 60 Добавление второго дает мне: a: 2: {i: 0; s: 2:” 60″; I: 1; s: 2: ”57 ″;} // пользователи 60 и 57 Это функционально для моей цели.Я бы хотел, чтобы код делал то же самое.

Но ... используя приведенный выше код для добавления одного пользователя, в поле current_mentees / DB я вижу 60. И затем, добавив 2-го, я получаю: 1: {я: 0; я: 57;}.(Он заменяет первого вместо добавления второго пользователя).

Я не уверен, что это начинается неправильно (с первым пользователем), или мне нужно изменить свои переменные в какой-то момент додобавив 2-й (который я пробовал).Спасибо!

1 Ответ

0 голосов
/ 02 октября 2018

Хорошо, я подумал о паре идей, которые можно попробовать этим утром, и все сошлось.Позвольте мне опубликовать мой пересмотренный код.По сути, я пытался следовать естественному форматированию, чтобы посмотреть, смогу ли я добиться того, чтобы все шло дальше.Я решил преобразовать исходную переменную в массив, и именно это заставило все остальное упасть в линию.

// 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);
...