How to add "Recent Posts" widget to the blog demo

It seems to be natural to have a function of "Recent Posts" above "Recent Comments", and here it is.

Posted Image

  • Save following code as blog/protected/components/RecentPosts.php.


[php]


<?php





class RecentPosts extends Portlet


{


        public $title='Recent Posts';





        public function getRecentPosts()


        {


                return Post::model()->findRecentPosts();


        }





        protected function renderContent()


        {


                $this->render('recentPosts');


        }


}


~~~  





* Save following code as `blog/protected/components/views/recentPosts.php`.


[php]

<ul>

<?php foreach($this->getRecentPosts() as $post): ?>

<li>

<?php echo CHtml::link(CHtml::encode($post->title),array('post/show','id'=>$post->id)); ?>

</li>

<?php endforeach; ?>

</ul>






* Add following method in the class of `Post` defined by `blog/protected/models/Post.php`.


[php]

      /**

        * @param integer the maximum number of comments that should be returned

        * @return array the most recently added comments

        */

        public function findRecentPosts($limit=10)

        {

          $criteria=array(

                          'condition'=>'Post.status='.self::STATUS_PUBLISHED,

                          'order'=>'Post.createTime DESC',

                          'limit'=>$limit,

                          );

          return $this->findAll($criteria);

        }






* Finally, place this widget above the recent comments widget. Modify 


`blog/protected/views/layouts/main.php` as follows. 


[php]

+    <?php $this->widget('RecentPosts'); ?>

    <?php $this->widget('RecentComments'); ?>






Have fun <img src='http://www.yiiframework.com/ipb/public/style_emoticons/default/wink.gif' class='bbc_emoticon' alt=';)' />


<hr class='bbc' />


[Updated: Feb 22, 2009]


Collection of the enhancements:


<a href='http://code.google.com/p/yii-blogdemo-enhanced/' class='bbc_url' title='External link' rel='nofollow'>http://code.google.c...gdemo-enhanced/</a>

I have changed it shown as a following code, though it requires Calendar widget extension.

blog/protected/components/views/recentPosts.php:

<ul>

<?php foreach($this->getRecentPosts() as $post): ?>

<li>

<?php echo CHtml::link(CHtml::encode($post->title),array('post/show','id'=>$post->id)); ?>

  • &nbsp;on&nbsp;

  • <?php echo CHTml::link(date('M j', $post->createTime), array('post/PostedOnDate', 'time'=>$post->createTime)); ?>

</li>

<?php endforeach; ?>

</ul>

You can get the latest version from the google code.