简体   繁体   中英

Joomla K2 - Get article link (SEF) by ID

How can I retrieve the SEF link of an article by its ID?

I think about a thing like this:

$link = get_link(34); // where 34 is the article ID

<a href="<?php echo $link; ?>">Article link</a>

UPDATE My code is this (updated with Rikesh code):

Mysql query: "SELECT id, title, extra_fields FROM xxxxx_k2_items WHERE catid = ".$catid

$n=0; //counter
while($row = mysql_fetch_array($result)){
  $titles[$n] = $row['title'];
  $links[$n] = JRoute::_(ContentHelperRoute::getArticleRoute($row['id'], $catid));
  $n++;
}

Ok, now this retrieves links like /joomla/index.php/currentpage?id=4 where 4 is the correct id but the link doesn't work! It goes to a wrong page. My doubt is: your code works also for K2 articles? Because I'm working with K2 articles not default joomla articles. Edit: yes, I've checked my doubt, your code links to the Joomla articles by ID, but the IDs i'm using are for K2 articles! Notice: I'd need of the SEF link

you should include the K2 route

require_once(JPATH_SITE.DS.'components'.DS.'com_k2'.DS.'helpers'.DS.'route.php');

and you should update both the mysql query and the PHP code because you need info also from the k2 categories table, here is an example

$db = JFactory::getDBO();
$query = '
    SELECT 
        a.id AS id,
        a.extra_fields AS extrafields,
        a.catid AS catid,
        a.title AS title,
        a.introtext AS introtext,
        a.alias AS alias,
        c.alias AS catalias
    FROM 
        #__k2_items AS a 
        LEFT JOIN #__k2_categories AS c ON ( a.catid = c.id ) 
        WHERE a.published = 1 AND a.catid = '.$catid;
$db->setQuery($query);
$articles = $db->loadObjectList();
$n=0;
foreach ($articles as $article) {
    $titles[$n] = $article->title;
    $links[$n] = K2HelperRoute::getItemRoute($article->id.':'.urlencode($article->alias),$article->catid.':'.urlencode($article->catalias));
    $n++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM