<?php
/**
 * Adds CallOut_Quote widget.
 * make sure to include in lib/widgets.php
 */
class chLatestNews extends CustomWP_Widget {

  /**
   * Register widget with WordPress.
   */ 
  function __construct() {
    parent::__construct(
      'chLatestNews',                             // Base ID
      __('(ch)Widget Latest News'),                        // Name
      array( 'description' => __( 'The Widget with Latest News.' ), ),         // Args
      array( 
        'title'        => array('label'        => 'Display Name',
                                'input'         => '<input id="[%ID%]" name="[%NAME%]" class="[%CLASS%] widefat" type="text" value="[%VALUE%]" [%PLACEHOLDER%] />',
                                'defaultValue'  => 'Latest News',
                       ),
        )
    );
  }

  /**
   * Front-end display of widget.
   *
   * @see WP_Widget::widget()
   *
   * @param array $args     Widget arguments.
   * @param array $instance Saved values from database.
   */

  public function widget( $args, $instance ) {
    global $post;

    $title        = nl2br($instance['title']);

    $qargs = array(
      'posts_per_page'   => 2,
      'offset'           => 0,
      'orderby'          => 'post_date',
      'order'            => 'DESC',
      'include'          => '',
      'exclude'          => '',
      'meta_key'         => '',
      'meta_value'       => '',
      'post_mime_type'   => '',
      'post_parent'      => '',
      'post_status'      => 'publish',
      'suppress_filters' => true );

    $news = get_posts($qargs); 

    echo $args['before_widget'].$args['before_title'];

    echo $title.$args['after_title']; ?>
    <div class="latest-news"><ul><?php

    foreach ($news as $lnews) {      

      $post = $lnews;
      setup_postdata($post);

      ?>
      <li><?php 

        if ( has_post_thumbnail() ) {

          ?><figure><a href="<?php the_permalink(); ?>" alt="<?php echo esc_attr(get_the_title()); ?>"><?php the_post_thumbnail(); ?></a></figure><?php

        }

        ?>
        <div class="content">
          <div class="title"><a href="<?php the_permalink(); ?>" alt="<?php echo esc_attr(get_the_title()); ?>"><?php the_title(); ?></a></div>
          <div class="comments"><?php

            $comments_count = wp_count_comments( $post->ID );
            if ( $comments_count->approved == 0 ) {
              echo "No comment";
            } elseif ( $comments_count->approved == 1 ) {
              echo "1 comment";
            } else {
              echo $comments_count->approved.' comments';
            }

          ?></div>
        </div>
      </li>
      <?php
    }

    ?></ul></div><?php

    echo $args['after_widget'];

  }

} // class chLatestNews


// register widget
function register_chLatestNews() {
    register_widget( 'chLatestNews' );
}
add_action( 'widgets_init', 'register_chLatestNews' );