如何使用PHP将分类术语引用的值设置为多个术语?


7

此问题描述了如何使用PHP设置术语参考字段的值。但是,如果要将用户个人资料中的术语引用字段的值设置为多个术语,该怎么办?

我正在尝试将值设置为术语ID 27和28。这是到目前为止的代码:

$user->field_yourfield_name[LANGUAGE_NONE][0]['tid'] = 27;
user_save($user);

Answers:


7

假设该字段设置为接受多个记录...

$user->field_yourfield_name[LANGUAGE_NONE][0]['tid'] = 27;
$user->field_yourfield_name[LANGUAGE_NONE][1]['tid'] = 28;
// etc

或者,您可以像这样继续追加到数组(不知道下一个可用索引):

$user->field_yourfield_name[LANGUAGE_NONE][]['tid'] = 27;
$user->field_yourfield_name[LANGUAGE_NONE][]['tid'] = 28;

1

您可以分配一个包含实体元数据包装器的列表值。例如:

<?php
  $wrapper = entity_metadata_wrapper('user', $user);
  foreach ($wrapper->field_taxonomy_terms->getIterator() as $delta => $term_wrapper) {
    // $term_wrapper may now be accessed as a taxonomy term wrapper.
    $label = $term_wrapper->name->value();
    $tid = $term_wrapper->tid->value();
    // you can also set the values
    $term_wrapper->name = 'New label';
    $term_wrapper->tid = array(123, 1234); // or ...
    $term_wrapper->tid->set($tids_to_set);
  }
  $wrapper->save();
?>
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.