【问题标题】:WP update_option() from $_POST array来自 $_POST 数组的 WP update_option()
【发布时间】:2020-04-17 02:36:13
【问题描述】:

乍一看,这是一个简单的问题,因为我通常会毫无问题地这样做。但是,在这种情况下,由于表单使用重复块,$_POST 数组将具有未知数量的键。因此,我要做的是从 POST REQUEST 中获取所有键和值,并将它们格式化为一个数组,以便使用 update_option() 更新 WordPress 用户选项。

下面会从提交的表单中获取key和value..

foreach ($_POST as $key => $val) {
$newitem = array($key => $val);
// format the array items
}

但后来我试图让这些键和值自动填充一个数组,以便看起来像这个例子......

$new_options = array(
'fav_number' => $_REQUEST['fav_number'],
'fav_color' => $_REQUEST['fav_color'],
);
update_option($user->user_nicename . '_plugin_options', $new_options);

我尝试使用 foreach 来格式化传入的键和值以填充数组。我什至尝试过这种极其丑陋的方法作为一种“黑客”,但即使这样也无济于事......

$output = print_r($_POST, true);
$output = str_replace(array("[action] => submit", "\"", "    ", "[", "]", "> "), array("", "", "", "'", "'", "> '"), $output);
$output = str_replace(array("\n'", ""), array("', \n'", ""), $output);
$output = str_replace(array("Array\n(\n', ", "\n)"), array("", "'"), $output);

提交表单后,我得到的只是空白结果、每个结果中的“a”或错误。

谁能告诉我是否有办法正确有效地做到这一点?

【问题讨论】:

  • 我刚刚收到一般的 WordPress 错误,即我的网站出现问题。单击“了解更多..”链接提供的帮助很少。在这里通过另一个用户解决了它,但认为你至少应该得到回应。谢谢。

标签: php arrays wordpress string


【解决方案1】:

不知道按键的时候可以这样用

unset($_POST['action']);
$new_items = array();
foreach ($_POST as $key=>$val) {
    // format the array items
    $new_items[$key] = $val;
}
update_option($user->user_nicename . '_plugin_options', 
$new_items);

【讨论】:

    【解决方案2】:

    您可以在foreach中创建一个新数组:

    $new_options = [];
    foreach (['fav_number', 'fav_color'] as $key) {
        $val = $_POST[$key];
        // format the array items
        $new_options[$key] = $val;
    }
    update_option($user->user_nicename . '_plugin_options', $new_options);
    

    【讨论】:

      猜你喜欢
      • 2012-05-10
      • 1970-01-01
      • 2015-12-10
      • 2012-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多