<?php
/*
Plugin Name: Display Latest Post Widget
Author: M3HDI
Version: 1
*/

class RecentPosts extends WP_Widget {
	// constructor
    function RecentPosts() {
		parent::__construct( false, __( 'آخرین مطالب', 'RecentPosts' ), 'description=' . __( 'نمایش آخرین مطالب', 'RecentPosts' ) );
    }

	// widget form creation
	function form($instance) {

	if( $instance) {
		$title = esc_attr($instance['title']);
		$catid = esc_attr($instance['catid']);
		$postnumber = esc_attr($instance['postnumber']);
	} else {
		$title = '';
		$catid = '';
		$postnumber = '';
	}
	?>

	<p>
		<label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('عنوان', 'RecentPosts'); ?></label>
		<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
	</p>
	<p>
		<label for="<?php echo $this->get_field_id('catid'); ?>"><?php _e('شماره دسته بندی:', 'RecentPosts'); ?></label>
		<input class="widefat" id="<?php echo $this->get_field_id('catid'); ?>" name="<?php echo $this->get_field_name('catid'); ?>" type="number" value="<?php echo $catid; ?>" step="any" />
	</p>
	<p>
		<label for="<?php echo $this->get_field_id('postnumber'); ?>"><?php _e('تعداد مطالب:', 'RecentPosts'); ?></label>
		<input class="widefat" id="<?php echo $this->get_field_id('postnumber'); ?>" name="<?php echo $this->get_field_name('postnumber'); ?>" type="number" value="<?php echo $postnumber; ?>" step="any" />
	</p>

	<?php }

	// update widget
	function update($new_instance, $old_instance) {
		$instance = $old_instance;
		// Fields
		$instance['title'] = strip_tags($new_instance['title']);
		$instance['catid'] = strip_tags($new_instance['catid']);
		$instance['postnumber'] = strip_tags($new_instance['postnumber']);
		return $instance;
	}

	// Display widget
	function widget($args, $instance) {
		extract( $args );
		// these are the widget options
		$title = apply_filters('widget_title', $instance['title']);
		$catid = $instance['catid'];
		$postnumber = $instance['postnumber'];
		echo $before_widget;

		// Check if title is set
		if ( $title ) {
			echo $before_title . $title . $after_title;
		}

		// Check if Category ID is set
		if( $catid ) {

			// WIDGET CODE START
			$recentPosts = new WP_Query( array( 'posts_per_page' => $postnumber,'cat' => $catid ) );  ?>
			<ul>
				<?php while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?>
				<li>
					<h4><a target="_blank" href="<?php the_permalink();?>"><?php if (strlen($post->post_title) > 90) { echo mb_substr(the_title($before = '', $after = '', FALSE), 0, 60) . '...'; } else { the_title(); } ?></a></h4>
				</li>
				<?php endwhile; ?>
			</ul>
			<?php wp_reset_query();
			// WIDGET CODE END

		}

		echo $after_widget;
	}
}

// register widget
add_action('widgets_init', create_function('', 'return register_widget("RecentPosts");')); ?>