Page 1 of 1

User tag to get random news item

Posted: Wed May 11, 2005 11:56 am
by kmoon
Hello,

I have been trying to wrote a usertag that will gram a random news item, but no matter what I try nothing shows up.
I'm not much of a programmer so I need some help here.

Here's my code:

Code: Select all

      global $gCms;
      $db = & $gCms->db;

      $dbresult = array();

      $query = "SELECT * FROM ".cms_db_prefix()."module_new 
 where news_cat = 'Udtalelser' ORDER BY RAND limit 1";
      $dbresult = $db->Execute($query);

      if ($dbresult && $dbresult->RowCount() > 0)
      {
         while ($row = $dbresult->FetchRow())
         {
            $name = $row[news_title];
            $data = $row[news_data];
            echo $data."<br>".$name;
        }
      }

Re: User tag to get random news item

Posted: Wed May 11, 2005 12:11 pm
by Ted
The table name is module_news instead of module_new.

It should be "ORDER BY rand()" as rand is a function.

Re: User tag to get random news item

Posted: Wed May 11, 2005 12:43 pm
by kmoon
Thanks...
After fighting with this for an hour I took a break and a cup of coffee.. when I came back I found those same mistakes.
Feeling stooopid...

Re: User tag to get random news item

Posted: Wed Sep 06, 2006 4:15 pm
by olaf_noehring
Hi

probably a better solution is to reuse the existing news module and simply add a new sortorder  8). Here the code - you need to add the new sortby-variable (random -> e.g. sortby="random") to the help yourself.

1. open /modules/news/action.default.php (from 1.0 beta 6)
2. searchif (isset($params['sortby']))
{
if ($params['sortby'] == 'news_category')
{
    $query .= "ORDER BY 'long_name', 'news_date'";
} else {
        $query .= "ORDER BY '" . str_replace("'", '', str_replace(';', '', $params['sortby'])) . "' ";
}
}
else
{
$query .= "ORDER BY news_date ";


3. replace withif (isset($params['sortby']))
{
//noehring - added random sort order for news
if ($params['sortby'] == 'random'){
$query .= "ORDER BY rand()";
} else {
if ($params['sortby'] == 'news_category')
{
    $query .= "ORDER BY 'long_name', 'news_date'";
} else {
        $query .= "ORDER BY '" . str_replace("'", '', str_replace(';', '', $params['sortby'])) . "' ";
}
}
// end noehring
}
else
{
$query .= "ORDER BY news_date ";
}


That's all!
Code posted in developers section under: http://dev.cmsmadesimple.org/tracker/in ... 8&atid=111
Olaf