我很难想出如何将用户元数据保存到帖子中。
我试图实现的目标是,让用户从下拉列表中进行选择,然后保存他的选择。当用户返回到该页面时,它将加载上次保存的选择。我的第一个想法是通过添加元数据来实现这一点。因此,基本上我所拥有的是以下内容。
\'$user_selection = array($user_ID => $the_users_choice)\'
更新并将其添加到meta是我遇到问题的地方。我需要$user\\u ID是唯一的,如果它在meta中不存在,那么wordpress将添加它,如果它存在,那么wordpress将更新该值(\\u useres\\u选项)。目前,它只是不断向数组末尾添加值。我在下面附上了我的全部代码。
if( \'POST\' == $_SERVER[\'REQUEST_METHOD\'] && !empty( $_POST[\'action\'] ) && $_POST[\'action\'] == "new_post") {
if (isset ($_POST[\'charity_name_form\'])) {
$title = $_POST[\'charity_name_form\'];
$user_ID = get_current_user_id();
$user_choice = array($user_ID => $title);
add_post_meta(get_the_ID(), \'user_charity\', $user_choice);
} else {
echo \'Please Select a Charity;
}
}
SO网友:Derrick Workman
所以我真的想得太多了。希望我的回答能对将来的人有所帮助。基本上,我所需要做的就是从wordpress保存数组,并检查user\\u ID(关联数组键)是否在数组中,如果在数组中,用户需要更改我在整个数组中搜索所需的值,替换该值并更新该数组。如果用户以前从未进行过选择,只需将其选择添加到数组中即可。
<?php
if( \'POST\' == $_SERVER[\'REQUEST_METHOD\'] && !empty( $_POST[\'action\'] ) && $_POST[\'action\'] == "new_post") {
// Do some minor form validation to make sure there is content
if (isset ($_POST[\'charity_name_form\'])) {
$title = $_POST[\'charity_name_form\'];
$user_ID = get_current_user_id().\'_ID\';
$user_choice = array($user_ID => $title);
$meta = get_post_meta( get_the_ID(), \'user_charity\');
$array_location = $meta[0];
// THIS CHECKS TO SEE IF USER HAS MADE A SELECTION BEFORE, IF HE HAS AND UPDATES HIS SELECTION THE VALUE CHANGES
if (isset( $array_location[$user_ID])){
$new_array = array();
foreach ($array_location as $key => $values){
$new_array[$key] = $values;
}
$new_array[$user_ID] = $title;
update_post_meta(get_the_ID(), \'user_charity\', $new_array);
}
// IF USER NEVER SELECTED A CHARITY HE SELECTS ONE
else {
// TAKES OLD ARRAY AND PUTS IT IN NEW EDITABLE VARIABLE
$new_array_add = array();
foreach ($array_location as $key => $values){
$new_array_add[$key] = $values;
}
// ADDS THE NEW USER SELECTION TO THE PREVIOUSLY SAVED ARAY
$new_array_add[$user_ID] = $title;
// UPDATES THE META WITH THE NEW ARRAY VARIABLE
update_post_meta(get_the_ID(), \'user_charity\', $new_array_add);
}
}
}
?>