Answers:
您可以EntityFieldQuery
用来检索节点列表,然后使用以下命令更新节点的字段node_save()
:
$lang = LANGUAGE_NONE; // Replace with ISO639-2 code if localizing
$node_type = 'page'; // Machine name of the content type
$query = new EntityFieldQuery;
$result = $query
->entityCondition('entity_type', 'node')
->propertyCondition('type', $node_type)
->execute();
if (!empty($result['node'])) {
$nodes = entity_load('node', array_keys($result['node']));
foreach($nodes as $node) {
// Replace field_foo with the machine name of the field to update.
// - 0 refers to specific value within the field array, for when the field contains
// multiple values. If the field only has one value, it should be 0.
$node->field_foo[$lang][0]['value'] = 'New Value';
node_save($node);
}
}
如果这是一次性操作,则可以使用Devel模块的Execute PHP函数来运行上述操作:否则,可以创建一个简单的自定义模块。
我将使用Views Bulk Operations并使用“ Execute Arbitrary PHP Script”基本上执行上述各项,但是您不必执行所有额外的代码,只需执行您想要的代码的小片段(如$object->field_foo['und'][0]['value'] = 'some_value'
)
如果您只想更新具有某些值的字段,则可以采用性能更高的替代答案:
$lang = LANGUAGE_NONE; // Replace with ISO639-2 code if localizing
$node_type = 'page'; // Machine name of the content type
$query = new EntityFieldQuery;
$result = $query
->entityCondition('entity_type', 'node')
->propertyCondition('type', $node_type)
->execute();
if (!empty($result['node'])) {
$nodes = entity_load('node', array_keys($result['node']));
foreach($nodes as $node) {
// Replace field_foo with the machine name of the field to update.
// - 0 refers to specific within the field array, for when the field contains
// multiple values. If the field only has one value, it should be 0.
$node->field_foo[$lang][0]['value'] = 'New Value';
field_attach_presave('node', $node);
field_attach_update('node', $node);
}
}
区别在于直接使用field_attach_presave
和field_attach_update
函数,它们仅正确更新节点字段,而跳过其余的节点保存过程。这样会产生影响,不会调用任何节点的presave / save挂钩,“更改的”日期不会更新为当前日期,等等。根据您的用例,最好使用整个node_save()过程。