wordpress 在 plugin 里定义一个 widget

来源:互联网 发布:淘宝商城专业托管 编辑:程序博客网 时间:2024/05/21 09:15

因为在加载plugin的时候,还没有完全加载完wordpress,导致 global $wp_widget_factory 为 NULL, 所以需要如下方式解决:

add_action('widgets_init', 'F_Home_Video');function F_Home_Video(){register_widget('F_Home_Video_Widget');}class F_Home_Video_Widget extends WP_Widget {function F_Home_Video_Widget() {parent::WP_Widget(false, $name = 'Home video widget');}function widget($args, $instance) {extract( $args );global $wpdb;$count = $instance['count'];$r = array('numberposts' => $count, 'category' => 3,'orderby' => 'post_date','order' => 'DESC', 'post_type' => 'post',);$posts = get_posts($r);if( empty($posts) ) return;        ?>              <?php echo $before_widget; ?>                  <?php echo $before_title                      . apply_filters('the_title', $instance['title'])                      . $after_title; ?><ul class="flowwidgets"><?phpforeach($posts as $post){setup_postdata($post);$attachment_url = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );$url = $attachment_url['0'];echo '<li><a><img src="'.$url.'" /></a><h2>'.get_the_title($post->ID).'</h2>'.the_content($post->ID).'</li>';}?></ul>              <?php echo $after_widget; ?>        <?php}function update($new_instance, $old_instance) {return $new_instance;}function form($instance) {$title = esc_attr($instance['title']);$count = esc_attr($instance['count']);        ?>            <p><label for="<?php echo $this->get_field_id('count'); ?>"><?php _e('Display Number:'); ?><input class="widefat" id="<?php echo $this->get_field_id('count'); ?>" name="<?php echo $this->get_field_name('count'); ?>" type="text" value="<?php echo $count; ?>" /></label></p>        <?php }}


原创粉丝点击