您可以使用以下代码编写自己的插件,尽管此功能应该已经是 joomla 核心的一部分。
我使用它是因为在使用其插入内容表单时出现 Seblod 错误。
文件:
Joomla 安装程序描述符:
uniqueAliasGenerator.xml
<?xml version="1.0" encoding="utf-8"?>
<extension version="3.1" type="plugin" group="content" method="upgrade">
<name>Content - Unique alias generator</name>
<author>McGiogen</author>
<creationDate>May 2015</creationDate>
<copyright></copyright>
<license></license>
<authorEmail>mcgiogen@hotmail.it</authorEmail>
<authorUrl>www.joomla.org</authorUrl>
<version>1.0</version>
<description>
Automatic generator of unique alias.
At save time it append "-X" (where X is a numeric identifier)
if article alias is already in database.
</description>
<files>
<filename plugin="uniqueAliasGenerator">uniqueAliasGenerator.php</filename>
<filename>index.html</filename>
</files>
<config>
</config>
</extension>
插件代码:
uniqueAliasGenerator.php
<?php
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
class plgContentUniqueAliasGenerator extends JPlugin
{
/**
* Alias check and generation before save content method.
* Content is passed by reference. Method is called before the content is saved.
*
* @param string $context The context of the content passed to the plugin (added in 1.6).
* @param object $article A JTableContent object.
* @param bool $isNew If the content is just about to be created.
*
* @return void
*/
public function onContentBeforeSave($context, $article, $isNew)
{
if ($context == 'com_content.article' && $article->alias && $isNew) {
$oldAlias = $article->alias;
$categoryId = $article->catid; //An alias must be unique only in its category
$article->alias = $this->getUniqueAlias($oldAlias, $categoryId);
}
return true;
}
/**
* Find unique Alias name if current doesn't exist.
* @param string $alias Alias of the article
* @param string $catId Id of article's category
*
* @return string Return the unique alias value.
*/
protected function getUniqueAlias($alias, $catId)
{
$alias_ini = $alias;
for ($i = 2; $this->isAliasExist($alias, $catId); $i++) {
$alias = $alias_ini . '-' . $i;
}
return $alias;
}
/**
* Check the 'alias' in the database.
*
* @return boolean If found return true else false.
*/
protected function isAliasExist($alias, $catId)
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query
->select('COUNT(*)')
->from($db->quoteName('#__content')) //Articles table
->where($db->quoteName('alias') . ' = ' . $db->quote($alias))
->where($db->quoteName('catid') . ' = ' . $db->quote($catId)); //Category ID
$db->setQuery($query);
return ($db->loadResult() ? true : false);
}
}
?>
index.html
<!DOCTYPE html><title></title>
使用方法:
创建具有相同名称的文件,将它们放在一个名为“uniqueAliasGenerator”的文件夹中,压缩到“uniqueAliasGenerator.zip”,上传并安装在您的joomla上。
与 Joomla 3.x 兼容,在 Joomla 3.4.1 上测试
2017 年 11 月 11 日更新
添加了 $isNew 的检查。谢谢@robert-drygas。