[skratchdot.]

NOTE: This post is referring to my old Wordpress blog. The theme has since changed.

When creating this blog’s theme, I decided I wanted the links in the side navigation to take up the full width of the navigation. Also, when hovering, I wanted to highlight the whole link/line. This seems like a very simple thing to do with CSS, but by default, a few of the Wordpress widgets do not allow for easy customization of the placement of the post count. This makes it hard to create sidebar entries in which the whole line is a link.

For example, by default, I could only get the Archive Widget to print out links in the following format:

<li><a href="/2009/09/">September 2009</a>&nbsp;(1)</li>

I wanted the links to be in this format (note the (1) is inside the anchor tag):

<li><a href="/2009/09/">September 2009&nbsp;(1)</a></li>

Below are the steps I took to override the default behavior of the Archive Widget. For this tutorial, I’m going to modify the “classic” theme that is provided with Wordpress 2.8. You can download both the original “classic” theme as well as my modified version “classic-modified” here.

NOTE: For detailed instructions on creating a Wordpress theme, there are many tutorials online. Also, the Wordpress.org site has fairly detailed documentation. The first tutorial I found via a google search was for entry level Wordpress developers, yet it was very helpful: www.wpdesigner.com.
 

For this tutorial, the first step to take is to copy the “classic” theme. Rename the copy “classic-modified” and place it in your themes folder.

Now we’re going to modify the functions.php file by adding lines 17-18 below:

 1 <?php
 2 /**
 3  * @package WordPress
 4  * @subpackage Classic_Theme
 5  */
 6 
 7 automatic_feed_links();
 8 
 9 if ( function_exists('register_sidebar') )
10 	register_sidebar(array(
11 		'before_widget' => '<li id="%1$s" class="widget %2$s">',
12 		'after_widget' => '</li>',
13 		'before_title' => '',
14 		'after_title' => '',
15 	));
16 
17 // Include the script that replaces the default archive widget
18 require_once('functions-widgets.php');
19 
20 ?>

Now create a blank file called functions-widgets.php and place it in your themes folder. Next, open the file “/wp-includes/default-widgets.php” and copy lines 210-271. Paste these lines in functions-widgets.php so it looks like the code below (Note I’ve added the opening and closing php tags):

 1 <?php
 2 
 3 /**
 4  * Archives widget class
 5  *
 6  * @since 2.8.0
 7  */
 8 class WP_Widget_Archives extends WP_Widget {
 9 
10 	function WP_Widget_Archives() {
11 		$widget_ops = array('classname' => 'widget_archive', 'description' => __( 'A monthly archive of your blog&#8217;s posts') );
12 		$this->WP_Widget('archives', __('Archives'), $widget_ops);
13 	}
14 
15 	function widget( $args, $instance ) {
16 		extract($args);
17 		$c = $instance['count'] ? '1' : '0';
18 		$d = $instance['dropdown'] ? '1' : '0';
19 		$title = apply_filters('widget_title', empty($instance['title']) ? __('Archives') : $instance['title']);
20 
21 		echo $before_widget;
22 		if ( $title )
23 			echo $before_title . $title . $after_title;
24 
25 		if ( $d ) {
26 ?>
27 		<select name="archive-dropdown" onchange='document.location.href=this.options[this.selectedIndex].value;'> <option value=""><?php echo esc_attr(__('Select Month')); ?></option> <?php wp_get_archives(apply_filters('widget_archives_dropdown_args', array('type' => 'monthly', 'format' => 'option', 'show_post_count' => $c))); ?> </select>
28 <?php
29 		} else {
30 ?>
31 		<ul>
32 		<?php wp_get_archives(apply_filters('widget_archives_args', array('type' => 'monthly', 'show_post_count' => $c))); ?>
33 		</ul>
34 <?php
35 		}
36 
37 		echo $after_widget;
38 	}
39 
40 	function update( $new_instance, $old_instance ) {
41 		$instance = $old_instance;
42 		$new_instance = wp_parse_args( (array) $new_instance, array( 'title' => '', 'count' => 0, 'dropdown' => '') );
43 		$instance['title'] = strip_tags($new_instance['title']);
44 		$instance['count'] = $new_instance['count'] ? 1 : 0;
45 		$instance['dropdown'] = $new_instance['dropdown'] ? 1 : 0;
46 
47 		return $instance;
48 	}
49 
50 	function form( $instance ) {
51 		$instance = wp_parse_args( (array) $instance, array( 'title' => '', 'count' => 0, 'dropdown' => '') );
52 		$title = strip_tags($instance['title']);
53 		$count = $instance['count'] ? 'checked="checked"' : '';
54 		$dropdown = $instance['dropdown'] ? 'checked="checked"' : '';
55 ?>
56 		<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></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 esc_attr($title); ?>" /></p>
57 		<p>
58 			<input class="checkbox" type="checkbox" <?php echo $count; ?> id="<?php echo $this->get_field_id('count'); ?>" name="<?php echo $this->get_field_name('count'); ?>" /> <label for="<?php echo $this->get_field_id('count'); ?>"><?php _e('Show post counts'); ?></label>
59 			<br />
60 			<input class="checkbox" type="checkbox" <?php echo $dropdown; ?> id="<?php echo $this->get_field_id('dropdown'); ?>" name="<?php echo $this->get_field_name('dropdown'); ?>" /> <label for="<?php echo $this->get_field_id('dropdown'); ?>"><?php _e('Display as a drop down'); ?></label>
61 		</p>
62 <?php
63 	}
64 }
65 
66 ?>

Now rename:

9 class WP_Widget_Archives extends WP_Widget {

to:

9 class MyTheme_Widget_Archives extends WP_Widget {

We did this because we are effectively creating a new widget, so if we want to use the old “Archives” widget, we can.

Now change the following function from:

11 function WP_Widget_Archives() {
12 		$widget_ops = array('classname' => 'widget_archive', 'description' => __( 'A monthly archive of your blog&#8217;s posts') );
13 		$this->WP_Widget('archives', __('Archives'), $widget_ops);
14 	}

to:

11 function MyTheme_Widget_Archives() {
12 		$widget_ops = array('classname' => 'widget_archive', 'description' => __( 'A monthly archive of your blog&#8217;s posts') );
13 		$this->WP_Widget('mytheme_archives', __('MyTheme Archives'), $widget_ops);
14 	}

Notice that we not only changed the function name, but we changed the parameters to the WP_Widget call. We did this for the same reason explained above (this is a “new” widget, and we want to be able to switch back to the old version).

 

For this next step, we are going to modify the widget(), form(), and update() calls. These are the functions that display the actual widget in the sidebar, and also display the widget details in the WordPress admin console. For this new widget, I am always going to display the post count, and I’m never going to display the archive results as a dropdown, so I can remove a few of the variables that are in the default archive widget ($c, $count, $d, $dropdown). To achieve this, you can modify functions-widgets.php like so:

Before changes:

15 function widget( $args, $instance ) {
16 		extract($args);
17 		$c = $instance['count'] ? '1' : '0';
18 		$d = $instance['dropdown'] ? '1' : '0';
19 		$title = apply_filters('widget_title', empty($instance['title']) ? __('Archives') : $instance['title']);
20  
21 		echo $before_widget;
22 		if ( $title )
23 			echo $before_title . $title . $after_title;
24  
25 		if ( $d ) {
26 ?>
27 		<select name="archive-dropdown" onchange='document.location.href=this.options[this.selectedIndex].value;'> <option value=""><?php echo esc_attr(__('Select Month')); ?></option> <?php wp_get_archives(apply_filters('widget_archives_dropdown_args', array('type' => 'monthly', 'format' => 'option', 'show_post_count' => $c))); ?> </select>
28 <?php
29 		} else {
30 ?>
31 		<ul>
32 		<?php wp_get_archives(apply_filters('widget_archives_args', array('type' => 'monthly', 'show_post_count' => $c))); ?>
33 		</ul>
34 <?php
35 		}
36  
37 		echo $after_widget;
38 	}
39  
40 	function update( $new_instance, $old_instance ) {
41 		$instance = $old_instance;
42 		$new_instance = wp_parse_args( (array) $new_instance, array( 'title' => '', 'count' => 0, 'dropdown' => '') );
43 		$instance['title'] = strip_tags($new_instance['title']);
44 		$instance['count'] = $new_instance['count'] ? 1 : 0;
45 		$instance['dropdown'] = $new_instance['dropdown'] ? 1 : 0;
46  
47 		return $instance;
48 	}
49  
50 	function form( $instance ) {
51 		$instance = wp_parse_args( (array) $instance, array( 'title' => '', 'count' => 0, 'dropdown' => '') );
52 		$title = strip_tags($instance['title']);
53 		$count = $instance['count'] ? 'checked="checked"' : '';
54 		$dropdown = $instance['dropdown'] ? 'checked="checked"' : '';
55 ?>
56 		<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></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 esc_attr($title); ?>" /></p>
57 		<p>
58 			<input class="checkbox" type="checkbox" <?php echo $count; ?> id="<?php echo $this->get_field_id('count'); ?>" name="<?php echo $this->get_field_name('count'); ?>" /> <label for="<?php echo $this->get_field_id('count'); ?>"><?php _e('Show post counts'); ?></label>
59 			<br />
60 			<input class="checkbox" type="checkbox" <?php echo $dropdown; ?> id="<?php echo $this->get_field_id('dropdown'); ?>" name="<?php echo $this->get_field_name('dropdown'); ?>" /> <label for="<?php echo $this->get_field_id('dropdown'); ?>"><?php _e('Display as a drop down'); ?></label>
61 		</p>
62 <?php
63 	}
64 }
65  
66 ?>

After changes:

15 function widget( $args, $instance ) {
16 		extract($args);
17 		$title = apply_filters('widget_title', empty($instance['title']) ? __('Archives') : $instance['title']);
18  
19 		echo $before_widget;
20 		if ( $title )
21 			echo $before_title . $title . $after_title;
22  ?>
23 		<ul>
24 			// We will complete this in the next step
25 		</ul>
26 <?php
27 		}
28  
29 		echo $after_widget;
30 	}
31  
32 	function update( $new_instance, $old_instance ) {
33 		$instance = $old_instance;
34 		$instance['title'] = strip_tags($new_instance['title']);
35 
36 		return $instance;
37 	}
38  
39 	function form( $instance ) {
40 		//Defaults
41 		$instance = wp_parse_args( (array) $instance, array( 'title' => '') );
42 		$title = esc_attr( $instance['title'] );
43 ?>
44 		<p>
45 			<label for="<?php echo $this->get_field_id('title'); ?>"><?php _e( 'Title:' ); ?></label>
46 			<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; ?>" />
47 		</p>
48 <?php
49 	}
50 }
51  
52 ?>

Now there’s one final step. We need to actually display the archives. To do that, we need to modify the widget() function. In the last step, we were left with the following line:

23 <ul>
24 			// We will complete this in the next step
25 		</ul>

We are now going to complete this block of code. Open up “/wp-includes/general-template.php” and copy lines 799-825. Paste them into line 24 of functions-widgets.php which will give you:

23 <ul>
24 		if ( 'monthly' == $type ) {
25 			$query = "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts FROM $wpdb->posts $join $where GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC $limit";
26 			$key = md5($query);
27 			$cache = wp_cache_get( 'wp_get_archives' , 'general');
28 			if ( !isset( $cache[ $key ] ) ) {
29 				$arcresults = $wpdb->get_results($query);
30 				$cache[ $key ] = $arcresults;
31 				wp_cache_add( 'wp_get_archives', $cache, 'general' );
32 			} else {
33 				$arcresults = $cache[ $key ];
34 			}
35 			if ( $arcresults ) {
36 				$afterafter = $after;
37 				foreach ( (array) $arcresults as $arcresult ) {
38 					$url = get_month_link( $arcresult->year, $arcresult->month );
39 					$text = sprintf(__('%1$s %2$d'), $wp_locale->get_month($arcresult->month), $arcresult->year);
40 					if ( $show_post_count )
41 						$after = '&nbsp;('.$arcresult->posts.')' . $afterafter;
42 					$output .= get_archives_link($url, $text, $format, $before, $after);
43 				}
44 			}
45 		</ul>

The first thing you’ll notice is the if ( ‘monthly’ == $type ) statement. We can remove this clause, because the “custom archive plugin” will only show archives by month (I wanted to keep it simple- no need for other display types). Also, this code is using a few global variables ($wpdb, $wp_locale) that aren’t yet being used properly in our version of the widget() function. We need to modify functions-widgets.php again to have the following line which will declare our global variables for use inside the function:

function widget( $args, $instance ) {
		global $wpdb, $wp_locale;
		extract($args);

Also, when we copied code the first time, we didn’t copy a few of the variables being used ($where and $join). Modify functions-widgets.php like so (adding lines 25-27):

24 <ul>
25 		//filters
26 		$where = apply_filters('getarchives_where', "WHERE post_type = 'post' AND post_status = 'publish'", $r );
27 		$join = apply_filters('getarchives_join', "", $r);
28 
29 		$query = "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts FROM $wpdb->posts $join $where GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC $limit";

Another thing about the code we copied: we can ignore the $post_count variable (since we are always showing post counts). We also want to make sure the post count shows up inside our anchor tag. To accomplish that, we can change:

$url = get_month_link( $arcresult->year, $arcresult->month );
$text = sprintf(__('%1$s %2$d'), $wp_locale->get_month($arcresult->month), $arcresult->year);
if ( $show_post_count )
	$after = '&nbsp;('.$arcresult->posts.')' . $afterafter;
$output .= get_archives_link($url, $text, $format, $before, $after);

to:

$url = get_month_link( $arcresult->year, $arcresult->month );
$text = sprintf(__('%1$s %2$d'), $wp_locale->get_month($arcresult->month), $arcresult->year);
$text .= '&nbsp;('.$arcresult->posts.')' . $afterafter;
$output .= get_archives_link($url, $text, $format, '<li>', '</li>');

Also add the correct output line before the widget() function ends:

echo '<ul>' . $output . '</ul>';
		echo $after_widget;

Our hacked/modified version is almost complete. The last thing I’m going to do is register the new archive widget (and unregister the default version). Do so by adding the following mytheme_widget_init() function to functions-widgets.php, then calling it:

80 /**
81  * Registering MyTheme Widgets
82  * Removing a few default WordPress Widgets
83  *
84  * @since 1.0
85  */
86 function mytheme_widget_init() {
87 	// unregister some default widgets
88 	unregister_widget('WP_Widget_Archives');
89 
90 	// register my own widgets
91 	register_widget('MyTheme_Widget_Archives');
92 }
93 
94 add_action('widgets_init', 'mytheme_widget_init');

After completing the above steps, your post count will show up inside the anchor tag. One final (optional) step is modifying the style.css file so archive links are highlighted when hovering. For the “classic-modified” theme, I’m going to add:

371 /* Custom styles for archive widget */
372 .widget_archive,
373 .widget_archive ul,
374 .widget_archive ul li,
375 .widget_archive ul li ul,
376 .widget_archive ul li ul li { border:0px; margin:0px; padding:0px; list-style: none; display:block; }
377 .widget_archive ul li a,
378 .widget_archive ul li ul li a { display: block; border-bottom: 1px dotted #666; margin:0px; padding:0px; }
379 .widget_archive ul li a,
380 .widget_archive ul li a:link,
381 .widget_archive ul li a:visited,
382 .widget_archive ul li a:hover,
383 .widget_archive ul li a:active { text-decoration:none; }
384 .widget_archive ul li a:hover { background:#eee; }

Comparison of default archive widget behavior vs. modified version

BEFORE (default archive widget):

BEFORE (default archive widget)

AFTER (modified archive widget):

AFTER (modified archive widget)
Tagged with: PHPWordpress


blog comments powered by Disqus