2

我正在开发一个现有的 wordpress 网站。用户有字段“用户国家”(实际上,我不知道这个字段是如何在 wordpress 中创建的,但它可以工作)。在注册表中,用户可以选择一个特定的国家。然而,现在这个国家列表被注释定义为“任何地方”。它是在代码中显式创建的:

<option value="Afghanistan" <?php if($current_user->user_country == 'Afghanistan') echo 'selected';?>>Afghanistan</option>
            <option value="Albania" <?php if($current_user->user_country == 'Albania') echo 'selected';?>>Albania</option>
            <option value="Algeria" <?php if($current_user->user_country == 'Algeria') echo 'selected';?>>Algeria</option>
            <option value="American Samoa" <?php if($current_user->user_country == 'American Samoa') echo 'selected';?>>American Samoa</opt

等等

客户想要更改此列表(从国家到城市)。所以我需要添加其他值。我不想在代码中写下所有值。我想在 wp-admin 中创建一些包含这些值的列表。

创建预定义值列表的最佳方法是什么?这些不是帖子的自定义字段。

编辑: 我想将值存储在数据库中,因此管理员可以从 wp-admin 修改这些值。实际上,它是 DB 还是 XML 等其他选项并不重要。我只想在用户注册时将此列表显示为下拉列表,并希望 wp-admin 修改此列表的值。

另外,我想到了一个问题 - 在数据库中存储用户自定义字段(如国家或城市)是否是正常做法?或者也许可以在代码中明确定义它们?

4

1 回答 1

3

好吧,如果您希望管理员能够修改列表,那么 DB 可能是这里的最佳选择。

我会做这样的事情(在 WordPress 中):

// put a default (initial) list in the database, if there isn't one there yet
if(!get_option('my_country_list')){

  // store it as a |-delimited string, because WP serializes arrays,
  // and this would be too much here
  $data = 'Albania|Algeria|Disneyland|etc';

  update_option('my_country_list', $data);
}

现在,稍后您需要该列表的地方,只需从数据库中获取它:

$countries = get_option('my_country_list');

// turn it into an array
$countries = implode('|', $countries);

// generate the select field
$html = '';
foreach($countries as $country){

  $checked = '';

  if($current_user->user_country == $country)
    $checked = 'selected="selected"';

  $html .= sprintf('<option value="%1$s" %2$s> %1$s </option>', $country, $checked);
}

printf('<select> %s </select>', $html);

我想您还会有一些选项管理表单,管理员可以在其中修改此列表中的条目。这可能是一个文本区域。当它再次提交给你update_option()时(用 替换新行|

于 2013-01-24T14:44:58.783 回答