defaults = array( 'title' => esc_attr__( 'Posts', 'essential-widgets' ), 'post_type' => array( 'post' ), 'order' => 'DESC', 'orderby' => 'date', 'number' => 10, 'show_date' => false, 'show_author' => false, ); $widget_ops = array( 'classname' => 'essential-widgets ew-posts ewposts', 'description' => esc_html__( 'Displays a list of posts.', 'essential-widgets' ), ); $control_ops = array( 'id_base' => 'ew-posts', ); parent::__construct( 'ew-posts', // Base ID esc_html__( 'EW: Posts', 'essential-widgets' ), // Name $widget_ops, $control_ops ); } /** * Displays the widget control options in the Widgets admin screen. * * @since 1.0.0 * @access public * @param array $instance * @param void */ public function form( $instance ) { // Merge the user-selected arguments with the defaults. $instance = wp_parse_args( (array) $instance, $this->defaults ); //

defaults ); $loop = new \WP_Query( array( 'posts_per_page' => $instance['number'], 'post_type' => $instance['post_type'], 'order' => $instance['order'], 'orderby' => $instance['orderby'], 'no_found_rows' => true, 'post_status' => 'publish', 'ignore_sticky_posts' => true, ) ); if ( $loop->have_posts() ) : // Escape widget wrapper attributes. echo wp_kses_post( $args['before_widget'] ); // If a title was input by the user, display it safely. if ( ! empty( $instance['title'] ) ) { echo wp_kses_post( $args['before_title'] ); // Apply filters to title, then escape it for output $title = apply_filters( 'widget_title', $instance['title'], $instance, $this->id_base ); echo esc_html( $title ); echo wp_kses_post( $args['after_title'] ); } // Output the main content of the widget (shortcode output) echo wp_kses_post( $this->shortcode( $instance ) ); // Close the widget wrapper safely. echo wp_kses_post( $args['after_widget'] ); wp_reset_postdata(); endif; } public function shortcode( $atts ) { $atts = wp_parse_args( $atts, $this->defaults ); $loop = new \WP_Query( array( 'posts_per_page' => $atts['number'], 'post_type' => $atts['post_type'], 'order' => $atts['order'], 'orderby' => $atts['orderby'], 'no_found_rows' => true, 'post_status' => 'publish', 'ignore_sticky_posts' => true, ) ); $output = ''; // Only show this title in block element and not on widget. if ( isset( $atts['is_block'] ) && true === $atts['is_block'] && !empty( $atts['title'] ) ) { $output .= '

' . esc_html( $atts['title'] ) . '

'; } // Output the page list. $output .= ''; return $output; } } endif; if ( ! function_exists( 'ew_posts_register' ) ) : /** * Intiate About_Widget Class. * * @since 1.0.0 */ function ew_posts_register() { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound -- ew_ is this plugin's abbreviated prefix. register_widget( 'EW_Posts' ); } add_action( 'widgets_init', 'ew_posts_register' ); endif;