在 Joomla 3.1.1 中,这是我用来批量插入文章(和标签)的简化代码:
$table = JTable::getInstance('Content', 'JTable', array());
$data = array(
'title' => $my_title,
'introtext' => $my_introtext,
....
'metadata' => array(
...,
'tags' => $list_of_tag[id],
...,
),
);
$table->bind($data);
$table->check();
$table->store();
然后$list_of_tag[ids]
进入表单metadata
中的#_content 字段{"tags":[ids],"robots":"","author":"","rights":"","xreference":""}
。Joomla 还会处理其他相关的表格,例如#_contentitem_tag_map
, 等。
此方法在 Joomla 3.1.4 中不起作用,因为标签不再进入metadata
字段,新格式为{"robots":"","author":"","rights":"","xreference":""}
,即不再有tags
键。
有谁知道如何在 3.1.4 中以编程方式将标签插入 Joomla?谢谢,
完整代码更新:
在 3.1.1 中工作的完整代码,其中 $row['tags'] 是一个整数数组,对应于 #_tags 中的现有标签 ID,并且 $row 中的所有其他字段都已明确定义。
<?php
define( '_JEXEC', 1 );
define('JPATH_BASE', dirname(dirname(__FILE__)));
define( 'DS', DIRECTORY_SEPARATOR );
require_once (JPATH_BASE . DS . 'includes' . DS . 'defines.php');
require_once (JPATH_BASE . DS . 'includes' . DS . 'framework.php');
require_once (JPATH_BASE . DS . 'libraries' . DS . 'joomla' . DS . 'factory.php' );
define('JPATH_COMPONENT_ADMINISTRATOR', JPATH_BASE . DS . 'administrator' . DS . 'components' . DS . 'com_content');
$mainframe = JFactory::getApplication('site');
require_once (JPATH_ADMINISTRATOR.'/components/com_content/models/article.php');
$string = file_get_contents("items.json");
$json_str = json_decode($string, true);
$title_default = 'No Title';
$i = 0;
foreach($json_str as $row){
$table = JTable::getInstance('Content', 'JTable', array());
$data = array(
'title' => $row['title'][0],
'alias' => $row['alias'][0],
'introtext' => $row['content'],
'state' => 1,
'catid' => $row['catid'][0],
'created' => $row['pdate'],
'created_by' => 635,
'created_by_alias' => $row['poster'][0],
'publish_up' => $row['pdate'],
'urls' => json_encode($row['urls']),
'access' => 1,
'metadata' => array(
'tags' => $row['tags'],
'robots' => "",
'author' => implode(" ", $row['poster']),
'rights' => "",
'xreference' => "",
),
);
++$i;
// Bind data
if (!$table->bind($data))
{
$this->setError($table->getError());
return false;
}
// Check the data.
if (!$table->check())
{
$this->setError($table->getError());
return false;
}
// Store the data.
if (!$table->store())
{
var_dump($this);
$this->setError($table->getError());
return false;
}
echo 'Record ' . $i . ' for post ' . $data['alias'] . ' processed';
echo "\r\n";
}
?>
在阅读文档后,我尝试了不同的方法来重写代码:
将元数据下的 'tags' => $row['tags'] 行移动到其父数组,即:
... 'access' => 1, 'tags' => $row['tags'], 'metadata' => array( 'robots' => "", 'author' => implode(" ", $row['poster']), 'rights' => "", 'xreference' => "", ), ...
所以现在我们有 $data['tags'] 填充了一个整数数组,映射了现有的标签 ID,大概为 JTable store() 方法做好了准备;
- 除了方法一,jsonify $row['tags']。为此,我尝试了两种方法:
2.a)
...
$registry = new JRegistry();
$registry->loadArray($row['tags']);
$data['tags'] = (string) $registry;
...
2.b)
data['tags'] = json_encode(json_encode($row['tags']));
通过这些更改,我仍然无法为插入的文章添加标签。
艾琳:谢谢你的耐心!