• Hello Guys,

    I am a new bee to wordpress community. I have made a widget to select pages via selectbox to show on widget area. I have collect data & information from this community and made this up.
    Here is my function.
    I am gladly open for any criticism and idea for more improvement of the code & pattern.

    class Custom_Pages_Widgets extends WP_Widget{
      public function __construct(){
          $widget_ops = array(
                          'description' => __( "A list of your site’s Pages." )
                        );
        parent::__construct( 'custom_widget_pages', __( 'Widget Pages' ), $widget_ops );
      }
      public function widget( $args, $instance ){
        extract($args);
        $select = empty( $instance['select'] ) ? '' : $instance['select'];
        echo $args['before_widget'];
        echo $args['before_title'];
        ?>
        <div class="widget-list">
          <ul>
            <?php
              foreach ($select as $post_id) {
                echo '<li><a href="'.get_the_permalink($post_id).'">'.esc_attr(get_the_title($post_id)).'</a></li>';
              }
            ?>
          </ul>
        </div>
        <?php
        echo $args['after_title'];
        echo $args['after_widget'];
    
      }
      public function update( $new_instance, $old_instance ){
          $instance = $old_instance;
          $instance['select'] = esc_sql( $new_instance['select'] );
          return $instance;
      }
    
      public function form( $instance ){
          if( $instance )
            $select = $instance['select'];
          else
            $select ='';
    
          $get_page = get_pages( array(
              'order' => 'DESC',
              'posts_per_page' => 200,
              'post_status' => 'publish',
              'post_type' => 'page',
          ));
          if( $get_page ){
              printf(
                  '<select
                      multiple="multiple"
                      name="%s[]"
                      id="%s"
                      class="widefat"
                      size="10"
                      style="margin: 5px;">',
                  $this->get_field_name('select'),
                  $this->get_field_id('select')
              );
              foreach( $get_page as $page )
              {
                  printf(
                      '<option value="%s" class="widefat" %s>%s</option>',
                      $page->ID,
                      in_array( $page->ID, $select) ? 'selected="selected"' : '',
                      $page->post_title
                  );
              }
              echo '</select>';
          }
          else
              echo 'No Pages have found :(';
      }
    }
    add_action('widgets_init', 'custom_widget_pages');
    function custom_widget_pages(){
        register_widget('Custom_Pages_Widgets');
    }

    Regards Shaad… ?? ??

  • The topic ‘WordPress Custom Page Widget’ is closed to new replies.