Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. // Creating the widget
  2. class wpb_widget extends WP_Widget {
  3.  
  4. function __construct() {
  5. parent::__construct(
  6. // Base ID of your widget
  7. 'wpb_widget',
  8.  
  9. // Widget name will appear in UI
  10. __('WPBeginner Widget', 'wpb_widget_domain'),
  11.  
  12. // Widget description
  13. array( 'description' => __( 'Sample widget based on WPBeginner Tutorial', 'wpb_widget_domain' ), )
  14. );
  15. }
  16.  
  17. // Creating widget front-end
  18. // This is where the action happens
  19. public function widget( $args, $instance ) {
  20. $title = apply_filters( 'widget_title', $instance['title'] );
  21. // before and after widget arguments are defined by themes
  22. echo $args['before_widget'];
  23. if ( ! empty( $title ) )
  24. echo $args['before_title'] . $title . $args['after_title'];
  25.  
  26. // This is where you run the code and display the output
  27. echo __( 'Hello, World!', 'wpb_widget_domain' );
  28. echo $args['after_widget'];
  29. }
  30.  
  31. // Widget Backend
  32. public function form( $instance ) {
  33. if ( isset( $instance[ 'title' ] ) ) {
  34. $title = $instance[ 'title' ];
  35. }
  36. else {
  37. $title = __( 'New title', 'wpb_widget_domain' );
  38. }
  39. // Widget admin form
  40. ?>
  41. <p>
  42. <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
  43. <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
  44. </p>
  45. <?php
  46. }
  47.  
  48. // Updating widget replacing old instances with new
  49. public function update( $new_instance, $old_instance ) {
  50. $instance = array();
  51. $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
  52. return $instance;
  53. }
  54. } // Class wpb_widget ends here
  55.  
  56. // Register and load the widget
  57. function wpb_load_widget() {
  58. register_widget( 'wpb_widget' );
  59. }
  60. add_action( 'widgets_init', 'wpb_load_widget' );