class My_Widget extends WP_Widget { function __construct() { parent::__construct( 'my_widget', __('My Widget', 'text_domain'), array( 'description' => __( 'Displays the current date and time', 'text_domain' ) ) ); } public function widget( $args, $instance ) { echo date('F j, Y, g:i a'); } } register_widget( 'My_Widget' );
class Recent_Posts_Widget extends WP_Widget { function __construct() { parent::__construct( 'recent_posts_widget', __('Recent Posts Widget', 'text_domain'), array( 'description' => __( 'Displays a list of recent posts', 'text_domain' ) ) ); } public function widget( $args, $instance ) { $query = new WP_Query( array( 'post_type' => 'post', 'posts_per_page' => $instance['posts_per_page'], 'orderby' => 'date' ) ); if ( $query->have_posts() ) { echo '
This code creates a widget that displays a list of recent posts. The user can specify how many posts should be shown using a form field in the widget's settings. The widget uses WP_Query to query for posts and then displays them in a list. In both of these examples, WP_Widget is used to create a new widget class, define its properties and methods, and then register it with WordPress so that it can be added to widget areas throughout the site.