2

到目前为止,我正在以最不舒服的方式重新发明轮子。我能在我的直觉中感觉到,这有一天会破裂并给我带来很多痛苦。因此,我正在寻找一种更好的方法来获取文章别名并构建菜单项 url 或文章 url。是否没有 joomla api 调用可以使这更容易/更清洁/更面向未来?

/* Find article by alias */
$db =& JFactory::getDBO();
$sql = 'select id from #__content where alias=' . "'$alias'";
$db->setQuery($sql);
$row = $db->loadAssoc();
$artId = $row['id'];
if ($artId != null) {
  $artLink = 'index.php?option=com_content&view=article&id='.$artId;
  /* Find menu item by article id */
  $sql = 'select parent,alias from #__menu where link=' . "'$artLink'";
  $db->setQuery($sql);
  $row = $db->loadAssoc();
  $menuLink = '';
  while ($row != null) {
    $menuLink = '/' . $row['alias'] . $menuLink;
    $sql = 'select parent,alias from #__menu where id=' . $row['parent'];
    $db->setQuery($sql);
    $row = $db->loadAssoc();
    }
  $menuLink = 'index.php' . $menuLink;
  }

$articleUrl = ($menuLink != '') ? 'index.php' . $menuLink : JRoute::_($artLink);
4

1 回答 1

1

使用 JRoute?假设您仍然从别名开始,更“Joomla”的方式可能是这样的:

/* Find article by alias */
$db =& JFactory::getDBO();
$sql = 'select id from #__content where alias=' . $db->quote($alias);
$db->setQuery($sql);
$row = $db->loadAssoc();
$artId = $row['id'];
if ($artId != null) {
  $articleUrl = JRoute::_('index.php?option=com_content&view=article&id=' . $artId);
}

JRoute 的文档在这里: http ://api.joomla.org/Joomla-Framework/JRoute.html

如果别名中有引号,这也可以解决 SQL 转义问题;o

我还应该提到,如果您特别想要菜单链接 - 您需要将路径末尾的 '&itemid=' 位传递给 JRoute!当然,您无法从别名中获取该 itemid - 可以有多个菜单项指向同一篇文章;)。

于 2009-11-26T00:40:24.143 回答