<?php
// Creating the widget
class Aletheme_popular_Widget extends WP_Widget {

	function __construct() {
		parent::__construct(
		// Base ID of your widget
			'Aletheme_popular_Widget',

			// Widget name will appear in UI
			__('Aletheme popular posts Widget', 'aletheme'),

			// Widget description
			array( 'description' => __( 'A widget that display the popular posts.', 'aletheme' ), )
		);
	}

	// Creating widget front-end
	// This is where the action happens
	public function widget( $args, $instance ) {
		$title = apply_filters( 'widget_title', $instance['title'] );
		// before and after widget arguments are defined by themes
		echo $args['before_widget'];
		if ( ! empty( $title ) )
			echo $args['before_title'] . esc_attr($title) . $args['after_title'];
		?>

	<div class="car_popular clearfix">
		<p class="caption"><?php echo _e('POPULAR CAR','aletheme'); ?></p>
		<div class="posts cf">
			<?php wp_reset_postdata();;
			$query_list = new WP_Query(array( 'post_type' => 'listing','posts_per_page' => 4,'orderby'=>'comment_count'));
			if( $query_list->have_posts() ): while( $query_list->have_posts() ) : $query_list->the_post(); ?>
				<div class="item left">
					<a href="<?php the_permalink(); ?> ">
						<?php
						if( get_the_post_thumbnail($post->ID,'post-blog_p')) {
							echo get_the_post_thumbnail($post->ID,'post-blog_p');
						}
						else {
							?>
							<img src="http://placehold.it/102x70&amp;text=No+image" alt/>
					   <?php
						}
						?>
					</a>

					<h4>
						<a href="<?php the_permalink(); ?>">
							<?php $current_category = wp_get_post_terms($post->ID, 'brand-listing', array("fields" => "all"));
							if($current_category){
								foreach($current_category as $curcat){
									echo '<span>' . $curcat->name . '</span> ';
								}
							}
							the_title(); ?>
						</a>
					</h4>

					<span class="red-col">
						<?php the_time('Y'); ?>
					</span>
				</div>
			<?php endwhile; endif; wp_reset_postdata(); ?>
		</div>
	</div>
		<?php
		echo $args['after_widget'];
	}

	// Widget Backend
	public function form( $instance ) {
		if ( isset( $instance[ 'title' ] ) ) {
			//   $title = $instance[ 'title' ];
		}
		else {
			//  $title = __( 'New title', 'aletheme' );
		}
		// Widget admin form
		?>

	<?php
	}

	// Updating widget replacing old instances with new
	public function update( $new_instance, $old_instance ) {
		$instance = array();
		$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
		return $instance;
	}
} // Class wpb_widget ends here

// Register and load the widget
function aletheme_load_widget3() {
	register_widget( 'Aletheme_popular_Widget' );
}
add_action( 'widgets_init', 'aletheme_load_widget3' );
?>