我尝试了以下方法(其中列出了称为静态内容的自定义帖子类型):
<?php
add_action("widgets_init", array(\'Widget_name\', \'register\'));
class Widget_name {
function control(){
$custom_posts = new WP_Query();
$custom_posts->query(\'post_type=page_content&page_sections=Lastest\');
while ($custom_posts->have_posts()) : $custom_posts->the_post();
?>
<div class="block-7 border-top">
<h2><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( \'Permalink to %s\', \'twentyten\' ), the_title_attribute( \'echo=0\' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
<a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( \'Permalink to %s\', \'twentyten\' ), the_title_attribute( \'echo=0\' ) ); ?>" rel="bookmark"><?php the_post_thumbnail(); ?></a>
<p><?php the_excerpt(); ?></p>
</div>
<?php endwhile;
}
function widget($args){
echo $args[\'before_widget\'];
echo $args[\'before_title\'] . \'Your widget title\' . $args[\'after_title\'];
echo $args[\'after_widget\'];
}
function register(){
register_sidebar_widget(\'Widget name\', array(\'Widget_name\', \'widget\'));
register_widget_control(\'Widget name\', array(\'Widget_name\', \'control\'));
}
}
?>
但运气不好。小部件中没有显示任何内容。
有什么建议吗?
SO网友:janoChen
找到了方法(感谢Wordpress Codex):
/** @see WP_Widget::widget */
function widget($args, $instance) {
extract( $args );
$title = apply_filters(\'widget_title\', $instance[\'title\']);
?>
<?php echo $before_widget; ?>
<?php if ( $title )
echo $before_title . $title . $after_title; ?>
<?php // Create and run custom loop
$custom_posts = new WP_Query();
$custom_posts->query(\'post_type=page_content\');
while ($custom_posts->have_posts()) : $custom_posts->the_post();
?>
<h2><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( \'Permalink to %s\', \'twentyten\' ), the_title_attribute( \'echo=0\' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
<?php endwhile; ?>
<?php echo $after_widget; ?>
<?php
}
/** @see WP_Widget::update */
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance[\'title\'] = strip_tags($new_instance[\'title\']);
return $instance;
}
/** @see WP_Widget::form */
function form($instance) {
$title = esc_attr($instance[\'title\']);
?>
<p><label for="<?php echo $this->get_field_id(\'title\'); ?>"><?php _e(\'Title:\'); ?> <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; ?>" /></label></p>
<?php
}
} // class FooWidget
// register FooWidget widget
add_action(\'widgets_init\', create_function(\'\', \'return register_widget("FooWidget");\'));