wordpress 在 plugin 里定义一个 widget

本文介绍了一个自定义的WordPress小部件,用于展示特定分类中的最新文章,并以视频预览的形式呈现。该小部件通过注册和使用自定义类实现,能够设置显示的文章数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

因为在加载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">
				<?php
				foreach($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 
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值