这里有一个简短的例子:(编辑:我更新了一些忘记的标点符号)。
<?php
/*
Plugin Name: Recent posts per category loop
Plugin URI: http://en.bainternet.info
Description: answer to http://wordpress.stackexchange.com/questions/16616/recent-posts-per-category-loop
Author: Bainternet
Version: 1.0
Author URI: http://en.bainternet.info
*/
// Initialization function
function WP_Widget_display_widget_init()
{
new WP_Widget_display_widget();
}
// Your Class
class WP_Widget_display_widget extends WP_Widget
{
// Constructor
function WP_Widget_display_widget()
{
$widget_ops = array(\'description\' => __(\'recent-posts-per-category-loop\', \'display_widget\'));
$this->WP_Widget(\'display_widget\', __(\'Display_widget\'), $widget_ops);
}
// Display Widget
function widget($args, $instance) {
extract($args);
$title = attribute_escape($instance[\'title\']);
echo $before_widget.$before_title.$title.$after_title;
display_widget();
echo $after_widget;
}
// When Widget Control Form Is Posted
function update($new_instance, $old_instance)
{
if (!isset($new_instance[\'submit\']))
{
return false;
}
$instance = $old_instance;
$instance[\'title\'] = strip_tags($new_instance[\'title\']);
return $instance;
}
/* Your custom code starts here */
/* ---------------------------- */
/* Your Function */
function display_widget()
{
/* Your Code ----------------- */
function display_widget(){
//only run on home or category
$args[\'post_status\'] = \'published\';
$args[\'posts_per_page\'] = 5;
if (is_front_page()||is_home()|| is_category())
return \'\';
if (is_category()){
$args[\'cat\'] = (int)get_query_var(\'cat\');
}
$po = new WP_Query( $args );
$out = \'<ul>\';
while ($po->have_posts()){
$po->the_post();
$out .= \'<li><a href="\'. get_permalink($post->ID).\'" title="\'.get_the_title($post->ID).\'">\'.get_the_title($post->ID).\'</a></li>\';
}
$out .= \'</ul>\';
echo $out;
}
}
}
add_action(\'widgets_init\', \'WP_Widget_display_widget_init\');