我正在尝试使用 PHP 脚本在 Drupal 7 中创建节点,然后使用 Drush 执行。
虽然我能够创建带有标题的基本节点,但由于某种原因我无法设置正文。
我使用在其他论坛上找到的不同建议尝试了两种不同的方法。
第一种情况,直接设置节点元素:
...
$node->title = 'Your node title';
$node->body[$node->language][0]['value'] = "<p>this is a test</p>";
$node->body[$node->language][0]['summary'] = "body summary;
$node->body[$node->language][0]['format'] = 'full_html';
在第二种情况下,使用实体包装器:
$node_wrapper = entity_metadata_wrapper('node', $node);
$node_wrapper->body->set(array('value' => '<p>New content</p>', 'format' => 'full_html'));
在这两种情况下,我都按如下方式保存节点:
$node = node_submit($node);
node_save($node);
在这两种情况下,我都会发布一个新节点,但主体永远不会被设置或显示。
如何正确设置我保存的新节点的主体?
要使用包装器创建节点(需要实体模块),请尝试以下代码:
$entity_type = 'node';
$entity = entity_create($entity_type, array('type' => 'article'));
$wrapper = entity_metadata_wrapper($entity_type, $entity);
$wrapper->title = 'title';
$wrapper->body->value = 'body value';
$wrapper->body->summary = 'summary';
$wrapper->body->format = 'full_html';
$wrapper->save();
在 Сергей Филимонов 的示例中,他没有调用
node_object_prepare($node)
(需要节点->类型),这会设置一些默认值(是否启用评论、是否将节点提升到首页、设置作者等),因此方法之间存在差异。
$entity = entity_create($entity_type, array('type' => 'article'));
可以替换为
$entity = new stdClass();
$entity->type = 'article';
我在这里看到两个问题
如果是新节点,请使用 LANGUAGE_NONE 或您的站点语言。
对于新对象 $node->language 将为空,您会收到通知:
注意:未定义的属性:stdClass::$language
此代码对我有用:
$node = new stdClass();
$node->title = 'Your node title';
$node->type = 'article';
$node->language = LANGUAGE_NONE;
$node->body[$node->language][0]['value'] = '<p>this is a test</p>';
$node->body[$node->language][0]['summary'] = 'body summary';
$node->body[$node->language][0]['format'] = 'full_html';
$node = node_submit($node);
node_save($node);
始终在此处设置正确的节点捆绑类型 $node->type。它是节点内容类型的机器名称。
因此,转到管理/内容页面并查看包含新节点的行:
但是您可以尝试使用node_load()函数加载节点,使用var_dump()打印它并查看您的字段,可能是节点输出的问题。
同意 Сергей 的观点,只是想补充一下,还应该调用 node_object_prepare() :
https://api.drupal.org/api/drupal/modules%21node%21node.module/function/node_object_prepare/7.x
$node = new stdClass();
$node->type = 'article';
node_object_prepare($node);
然后设置其他值,标题,正文...
Error: Call to undefined function node_submit() in include()
Error: Call to undefined function entity_create()
Error: Call to undefined function node_object_prepare()
[error] Error: Undefined constant "LANGUAGE_NONE"
这些功能你想出来了吗?