a recent posts widget


In order to try and get a few more photos into the content, I wanted to have widget (which sits down the right hand side of the screen) which would display recent posts from either 1 particular category, all categories, or the specific category of the actual post being viewed. I couldn’t find anything out there that worked well so I wrote my own. The entire code is below. The screensho on the right shows what it looks like. [Ed, need to add the dynamic option to the code.]

<?php
/*
Plugin Name: Cape Ealing Recent Posts
Plugin URI: https://capeealing.com/2009/02/a-recent-posts-widget/
Description: This widget gets a defined number of recent posts for 1 or more categories with their pictures.
Author: Ben
Version: 1.0
Author URI: https://capeealing.com/
*/

function ce_recent_main ($ce_type, $ce_cat, $ce_numposts){

?>
<div class="gallery-stream section">
<?

//echo $ce_cat;
//echo $ce_type;
//echo $ce_numposts;

// is this just one category or all
if ($ce_type == 'one')
{
$recent_posts = get_posts('numberposts='.$ce_numposts.'&category='.$ce_cat.'&orderby=date&order=DESC');
}
else
{
$recent_posts = get_posts('numberposts='.$ce_numposts.'&orderby=date&order=DESC');
}

// loop through each posts and report its picture 

foreach($recent_posts as $post):

$args = array(
	'post_type' => 'attachment',
	'numberposts' => 1,
	'post_status' => null,
	'post_parent' => $post->ID
	);
$attachments = get_posts($args);
if ($attachments) {
	foreach ($attachments as $attachment) {
		echo apply_filters('the_title', $attachment->post_title);
//		the_attachment_link($attachment->ID, false);

          echo wp_get_attachment_link($attachment->ID, 'thumbnail', true);

          ?></br><?
	}
}

endforeach;
?>
</div>
<?

}     // end function ce_recent_main

/*
ce_recent_posts_widget( $args, $widget_args = 1 )
The function called by WordPress when widget is set up by administrator
*/
function ce_recent_posts_widget( $args, $widget_args = 1 ) {
	extract( $args, EXTR_SKIP );

          // Start up section common to all
	if ( is_numeric($widget_args) )
		$widget_args = array( 'number' => $widget_args );
	$widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) );
	extract( $widget_args, EXTR_SKIP );
	$options = get_option('widget_ce_recent_posts'); // Data for this instance of widget
	if ( !isset($options[$number]) )
		return;

	// Get the variables: title and cat_id
	$title = $options[$number]['title'];
	$type = $options[$number]['type'];
	$cat_id = empty($options[$number]['cat']) ? 1 : $options[$number]['cat'];
         $numposts = $options[$number]['numposts']; 

	// Set the title for the widget
	echo $before_widget;
	echo $before_title;
	echo $title;
	echo $after_title;

//	ce_recent_start($type, $post_orderby, $post_order);
         ce_recent_main($type, $cat_id, $numposts);
	echo $after_widget;
}

/*
ce_recent_posts_control( $widget_args = 1 )
This is the section for the WordPress control panel (admin panel) form.
This is where the widget settings are defined and then stored in the database.
Want to acknowledge Milan Petrovic's excellent tutorial on this found here:
http://wp.gdragon.info/2008/07/06/create-multi-instances-widget/
and the commenting this script by James Lao in his navigation tree widget:
http://jameslao.com/2008/04/18/category-posts-widget-13/
*/
function ce_recent_posts_control( $widget_args = 1 ) {

	// start-up procedures.  Unchanged across all 'multiple instances' widgets
	global $wp_registered_widgets;
	static $updated = false; 					// whether been updated yet.
	if ( is_numeric($widget_args) )
		$widget_args = array( 'number' => $widget_args );

	$widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) );
	extract( $widget_args, EXTR_SKIP );  		// extracts widget variables and their values (eg creates $number)

		$options = get_option('widget_ce_recent_posts');// get the correct details for all instances of the widget
	if ( !is_array($options) )  				// if there are no details then create an empty array
		$options = array();

	if ( !$updated && !empty($_POST['sidebar']) ) { 	// Not updated, post form not empty.  So need to update.
		$sidebar = (string) $_POST['sidebar'];   		// Tells us what sidebar to put the data in
		$sidebars_widgets = wp_get_sidebars_widgets();
		if ( isset($sidebars_widgets[$sidebar]) )
			$this_sidebar =& $sidebars_widgets[$sidebar];
		else
			$this_sidebar = array();

		foreach ( $this_sidebar as $_widget_id ) {		// Remove all widgets from the sidebar.  Added in again later.
			if ( 'ce_recent_posts_widget' == $wp_registered_widgets[$_widget_id]['callback'] && isset($wp_registered_widgets[$_widget_id]['params'][0]['number']) ) {
				$widget_number = $wp_registered_widgets[$_widget_id]['params'][0]['number'];
				if ( !in_array( "ce-recent-$widget_number", $_POST['widget-id'] ) ) // the widget has been removed. "many-$widget_number" is "{id_base}-{widget_number}
					unset($options[$widget_number]);
			}
		}

	// Write the data for each instance of the widget
		foreach ( (array) $_POST['ce-recent'] as $widget_number => $ce_recent_instance ) {
			$title = $ce_recent_instance['title'];
			$options[$widget_number] = array( 'title' => $title, 'type' => $ce_recent_instance['type'], 'cat' => (int) $ce_recent_instance['cat'], 'numposts' => $ce_recent_instance['numposts']);
		}

	update_option('widget_ce_recent_posts', $options); // update the particular key in the options database
	$updated = true; // So that we don't go through this more than once
	}

	// Having completed start-up, now show the form.
	// Populate with default values if necessary.
	if ( -1 == $number ) {
		$title = 'recent posts';
		$type = 'All';
		$cat = '';
		$numposts = 10;
		$number = '%i%';
	} else {
		$title = attribute_escape($options[$number]['title']);
		$type = $options[$number]['type'];
		$cat = (int) $options[$number]['cat'];
		$numposts = (int) $options[$number]['numposts'];
	}

	// Echo out the form.
	// Note: WordPress includes the $title in the heading for the control box.
	// The form has inputs with names like widget-many[$number][something] so that all data for that instance of
	// the widget are stored in one $_POST variable: $_POST['widget-many'][$number]
	// Work out which option should be pre-selected in form
    if ($type == "one")
		$sel1 = "Selected";

	?>
	<p>Set the parameters for the recent posts widget.</p>
    <p>
		<label for="ce-recent-title-<?php echo $number; ?>">
		<?php _e( 'Title:' ); ?>
		<input class="widefat" id="ce-recent-title-<?php echo $number; ?>" name="ce-recent[<?php echo $number; ?>][title]" type="text" value="<?php echo $title; ?>" />
		</label>
    </p>
	<p></p>
		<label><?php _e( 'All categories or just one:' ); ?><br />
			<select id="ce-recent-type-<?php echo $number; ?>" name="ce-recent[<?php echo $number; ?>][type]" value="<?php echo $type; ?>" >
				<option value="all" >All</option>
				<option <?php echo $sel1; ?> value="one" >One category</option>
			</select>
		</label>
	<p>
		<label>
			<?php _e( 'This one category only:' ); ?><br />
			<?php wp_dropdown_categories( array( 'name' => 'ce-recent[' . $number . '][cat]', 'selected' => $cat ) ); ?>
		</label>
	</p>
	<p>
		<label>
			<?php _e( 'How many posts to select:' ); ?><br />
			<input class="widefat" id="ce-recent-numposts-<?php echo $number; ?>" name="ce-recent[<?php echo $number; ?>][numposts]" type="text" value="<?php echo $numposts; ?>" />
			</label>    </p>

	<p></p>
		<!--<input type="hidden" name="ce-recent[<?php echo $number; ?>][submit]" value="1" />-->
<?php

}
/*
ce_recent_posts_register()
This function registers each instance of our widget on startup.
Want to acknowledge Milan Petrovic's excellent tutorial on this found here:
http://wp.gdragon.info/2008/07/06/create-multi-instances-widget/
and the commenting this script by James Lao in his navigation tree widget:
http://jameslao.com/2008/04/18/category-posts-widget-13/
*/
function ce_recent_posts_register() {

	// First check to see if there is a 'widget_ce_recent_posts' in the options table of the database.
	// If not, creat an empty $options array.
	if ( !$options = get_option('widget_ce_recent_posts') )
		$options = array();

	// Populate various easy reference variables
	$widget_ops = array('classname' => 'ce_recent', 'description' => __('Widget that displays recent posts.'));
	$control_ops = array('id_base' => 'ce-recent');
	$name = __('Cape Ealing Recents');

	// Set $registered as false (this is checked later to prevent running more than once).
	$registered = false;

	// Return each of the keys of the array '$options'
	foreach ( array_keys($options) as $o ) {
        // Checking whether a particular 'test' variable has been set, if not then continue
		if ( !isset($options[$o]['title']) )
			continue;

		// $id should look like {$id_base}-{$o}. Never translate an ID.
		$id = "ce-recent-$o";
		// now register
		$registered = true;
		wp_register_sidebar_widget( $id, $name, 'ce_recent_posts_widget', $widget_ops, array( 'number' => $o ) );
		wp_register_widget_control( $id, $name, 'ce_recent_posts_control', $control_ops, array( 'number' => $o ) );
	}											// End foreach

	// If not registered, then register with a generic template
	if ( !$registered ) {
		wp_register_sidebar_widget( 'ce-recent-1', $name, 'ce_recent_posts_widget', $widget_ops, array( 'number' => -1 ) );
		wp_register_widget_control( 'ce-recent-1', $name, 'ce_recent_posts_control', $control_ops, array( 'number' => -1 ) );
	}
}

/*
add_action( 'widgets_init', 'ce_recent_posts_register' )
This last action runs first and ensures the function 'ce_recent_posts_register' runs whenever the 'widgets_init' is run.
*/
add_action( 'widgets_init', 'ce_recent_posts_register' );
?>

post a comment...

you must be logged in to post a comment.