1

QUESTION#1

This thread is an extension of what has been discussed here, but since there the answer has been accepted so I am creating a new thread.

There comes a situation many times where we have to display the same widget in the vertical sidebar as well as a Horizontal sidebar. To make this happen flawlessly we have to tweak the CSS for one sidebar. Either we do it through some javascript or by some drop down/CHECKBOX arrangement in the widget form that can inscribe additional CSS for the horizontal or vertical sidebar. It is also advised that one should not pollify too much code with Javascript.

Let me explain one step further →

public function widget($args, $instance) {
    extract( $args );
    $title = apply_filters( 'widget_title', $instance['title'] );

/* Display the markup before the widget. */
echo $before_widget;
if ( $title ) {
    echo $before_title . $title . $after_title;
}
/* Create a custom query and get the most recent 4 projects. */
$queryArgs = array(
    /* Do not get posts from the Uncategorized category. */
    'cat' => '-1',
    /* Order by date. */
    'orderby' => 'date',
    /* Show all posts. */
    'posts_per_page' => '4'
);
$query = new WP_Query( $queryArgs );
if ( $query->have_posts() ) : ?>
    <ul class="unbullet">
    <?php while ( $query->have_posts() ) : $query->the_post(); ?>
        <li class="snippet-box">
            <div>
                <!-- <img src="http://heightandweights.com/wp-content/uploads/2014/10/Beautiful-Lindsey-Vonn.jpg" alt="" class="hundred"> -->
                <?php the_post_thumbnail( 'medium', array( 'class' => 'hundred' ) ); ?>
                <div class="snippet-text">
                    <h3><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3>
                    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
                </div>
            </div>
            <!-- <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail( 'large', array( 'class' => 'img-responsive' ) ); ?></a> -->
        </li>
    <?php endwhile; ?>
    </ul>
<?php endif;
/* Display the markup after the widget. */
echo $after_widget;
}

The above is a code that works successfully on the Horizontal sidebar, but if we wish to display this in the vertical sidebar then we have to add just two more classes namely →

  1. vertical

  2. unbullet-v

That means this <ul class="unbullet"> has to change to →

<ul class="unbullet unbullet-v">

and

this <li class="snippet-box"> has to change to this one

<li class="snippet-box vertical">

With the Help of this post I am able to create a checkbox in the backend form.

  1. I have successfully added this form in the widget form method →

<p>
        <input class="checkbox" type="checkbox" <?php checked( $instance[ 'vertical_sidebar_check' ], 'on' ); ?> id="<?php echo $this->get_field_id( 'vertical_sidebar_check' ); ?>" name="<?php echo $this->get_field_name( 'vertical_sidebar_check' ); ?>" />
        <label for="<?php echo $this->get_field_id( 'vertical_sidebar_check' ); ?>"><?php _e('Select for Vertical Sidebar', 'text-domain'); ?></label>
</p>

This in the widget update method →

$instance[ 'vertical_sidebar_check' ] = $new_instance[ 'vertical_sidebar_check' ];

but although I understand the logic, but don't know how to apply that in terms of PHP code.

And the logic in English is like this →

    <ul class="unbullet <?php If the check box is ticked then echo this class: unbullet-v ?> ">
        <li class="snippet-box ?php If the check box is ticked then echo this class:vertical ?> ">

BUT I HAVE NO CLUE HOW TO IMPLEMENT THE ABOVE LOGIC IN TERMS OF PURE PHP CODE.

LAST QUESTION: I also want to give an option in the backend for the posts to be displayed by the category filter that means a backend form method for category selection then widget update method and widget front end method will display posts based on the category selected.


Full Source Code of the Widget →

<?php
ini_set('display_errors',0);
error_reporting(E_ALL|E_STRICT);
class chimp_post_widget extends WP_Widget {
    function __construct() {
        //Create Widget
        parent::__construct(
            'post_display_widget',
            esc_html__('The Post Widget','text_domain'),
            array(
                'classname'       =>    'post-widget',
                'description'     =>    esc_html__('A Post Thumbnail Widget', 'text_domain' )
            )
        );
    }

    public function form( $instance ) {
       $title = isset( $instance['title'] ) ? $instance['title'] : '';
       $number_of_posts = isset( $instance['number_of_posts'] ) ? absint( $instance['number_of_posts'] ) : 5;
       $number_of_words = isset( $instance['number_of_words'] ) ? absint( $instance['number_of_words'] ) : 20;
       ?>
       <p><label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:', 'text_domain' ); ?></label>
       <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 ); ?>" /></p>

       <p><label for="<?php echo $this->get_field_id( 'number_of_posts' ); ?>"><?php _e( 'Number of projects to show:', 'text_domain' ); ?></label>
       <input class="tiny-text" id="<?php echo $this->get_field_id( 'number_of_posts' ); ?>" name="<?php echo $this->get_field_name( 'number_of_posts' ); ?>" type="number" step="1" min="1" value="<?php echo $number_of_posts; ?>" size="3" /></p>

       <p><label for="<?php echo $this->get_field_id( 'number_of_words' ); ?>"><?php _e( 'Set the word limit for project descriptions:', 'text_domain' ); ?></label>
       <input class="tiny-text" id="<?php echo $this->get_field_id( 'number_of_words' ); ?>" name="<?php echo $this->get_field_name( 'number_of_words' ); ?>" type="number" step="1" min="1" value="<?php echo $number_of_words; ?>" size="4" /></p>

       <p>
        <input class="checkbox" type="checkbox" <?php checked( $instance[ 'vertical_sidebar_check' ], 'on' ); ?> id="<?php echo $this->get_field_id( 'vertical_sidebar_check' ); ?>" name="<?php echo $this->get_field_name( 'vertical_sidebar_check' ); ?>" />
        <label for="<?php echo $this->get_field_id( 'vertical_sidebar_check' ); ?>"><?php _e('Select for Vertical Sidebar', 'text-domain'); ?></label>
      </p>


       <?php
    }

    public function update($new_instance, $old_instance) {
        $instance = $old_instance;
        $instance['title']           = sanitize_text_field( $new_instance['title'] );
        $instance['number_of_posts'] = absint( $new_instance['number_of_posts'] );
        $instance['number_of_words'] = absint( $new_instance['number_of_words'] );
        $instance[ 'vertical_sidebar_check' ] = $new_instance[ 'vertical_sidebar_check' ];
        return $instance;
    }

    public function widget($args, $instance) {
        extract( $args );
        $title = apply_filters( 'widget_title', $instance['title'] );

        /* Display the markup before the widget. */
        echo $args['before_widget'];
       if ( ! empty( $instance['title'] ) ) {
           echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ) . $args['after_title'];
       }

       $number_of_posts = ( ! empty( $instance['number_of_posts'] ) ) ? absint( $instance['number_of_posts'] ) : 5;
       if ( ! $number_of_posts ) {
           $number_of_posts = 5;
       }

       $number_of_words = ( ! empty( $instance['number_of_words'] ) ) ? absint( $instance['number_of_words'] ) : 20;
       if ( ! $number_of_words ) {
           $number_of_words = 20;
       }
        /* Create a custom query and get the most recent 4 projects. */
        $queryArgs = array(
            /* Do not get posts from the Uncategorized category. */
            'cat' => '-1',
            /* Order by date. */
            'orderby' => 'date',
            /* Show all posts. */
            'posts_per_page' => $number_of_posts,
        );
        $query = new WP_Query( $queryArgs );
        if ( $query->have_posts() ) : ?>
            <ul class="unbullet unbullet-v">
            <?php while ( $query->have_posts() ) : $query->the_post(); ?>
                <li class="snippet-box vertical">
                    <div>
                        <!-- <img src="http://heightandweights.com/wp-content/uploads/2014/10/Beautiful-Lindsey-Vonn.jpg" alt="" class="hundred"> -->
                        <?php the_post_thumbnail( 'medium', array( 'class' => 'hundred' ) ); ?>
                        <div class="snippet-text">
                            <h3><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3>
                            <p><?php echo wp_trim_words( get_the_excerpt(), $number_of_words , __( '&hellip;', 'text_domain' ) ); ?>
                                    </p>
                        </div>
                    </div>
                    <!-- <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail( 'large', array( 'class' => 'img-responsive' ) ); ?></a> -->
                </li>
            <?php endwhile; ?>
            </ul>
        <?php endif;
        /* Display the markup after the widget. */
        echo $after_widget;
    }
}

add_action('widgets_init', function(){
    register_widget('chimp_post_widget');
})
?>

we have to print or make these classes applicable only when the checkbox is ticked →

 1. unbullet-v 
 2. vertical
  • Fingers Crossed waiting to learn another chapter. Excited as a WP Novice. – The WP Novice May 4 '17 at 13:59
  • I tried this, but this generated error → <li class="snippet-box <?php if( vertical_sidebar_check AND vertical_sidebar_check == '1' ) {class='vertical'; } ?>"> – The WP Novice May 4 '17 at 18:49
  • 1
    Hi, I've added an answer for you! – Dave Romsey May 5 '17 at 20:07
1

Here is an updated version of the widget which handles the vertical layout option, including categories, and excluding categories.

Handling the vertical layout option is pretty straightforward; we just check to see if the option is checked, and if so, output the appropriate classes.

Handling the inclusion/exclusion of categories is a little more complex because we are taking those settings in from the user as strings (comma separated list of IDs) and converting those values into arrays for use in the WP_Query parameters category__in and category__not_in.

class chimp_post_widget extends WP_Widget {
    function __construct() {
            //Create Widget
            parent::__construct(
                    'post_display_widget',
                    esc_html__('The Post Widget','text_domain'),
                    array(
                            'classname'       =>    'post-widget',
                            'description'     =>    esc_html__('A Post Thumbnail Widget', 'text_domain' )
                    )
            );
    }

    public function form( $instance ) {
        $title = isset( $instance['title'] ) ? $instance['title'] : '';
        $number_of_posts = isset( $instance['number_of_posts'] ) ? absint( $instance['number_of_posts'] ) : 5;
        $number_of_words = isset( $instance['number_of_words'] ) ? absint( $instance['number_of_words'] ) : 20;

        $cat_include = isset( $instance['cat_include'] ) ? $instance['cat_include'] : '';
        $cat_exclude = isset( $instance['cat_exclude'] ) ? $instance['cat_exclude'] : '';

        $vertical_sidebar_check =  isset( $instance[ 'vertical_sidebar_check' ] ) && ( 'on' === $instance[ 'vertical_sidebar_check' ] ) ? 'on' : 'off';
        ?>
        <p><label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:', 'text_domain' ); ?></label>
        <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 ); ?>" /></p>

        <p><label for="<?php echo $this->get_field_id( 'number_of_posts' ); ?>"><?php _e( 'Number of projects to show:', 'text_domain' ); ?></label>
        <input class="tiny-text" id="<?php echo $this->get_field_id( 'number_of_posts' ); ?>" name="<?php echo $this->get_field_name( 'number_of_posts' ); ?>" type="number" step="1" min="1" value="<?php echo $number_of_posts; ?>" size="3" /></p>

        <p><label for="<?php echo $this->get_field_id( 'number_of_words' ); ?>"><?php _e( 'Set the word limit for project descriptions:', 'text_domain' ); ?></label>
        <input class="tiny-text" id="<?php echo $this->get_field_id( 'number_of_words' ); ?>" name="<?php echo $this->get_field_name( 'number_of_words' ); ?>" type="number" step="1" min="1" value="<?php echo $number_of_words; ?>" size="4" /></p>

        <p><label for="<?php echo $this->get_field_id( 'cat_include' ); ?>"><?php _e( 'Include Categories:', 'text_domain' ); ?></label>
        <input class="widefat" id="<?php echo $this->get_field_id( 'cat_include' ); ?>" name="<?php echo $this->get_field_name( 'cat_include' ); ?>" type="text" value="<?php echo esc_attr( $cat_include ); ?>" />
        <small>Comma separated list of category IDs to <strong>include</strong> in post query. e.g.: 11,17,347<br>If blank, all categories will be included.</small>
        </p>

        <p><label for="<?php echo $this->get_field_id( 'cat_exclude' ); ?>"><?php _e( 'Exclude Categories:', 'text_domain' ); ?></label>
        <input class="widefat" id="<?php echo $this->get_field_id( 'cat_exclude' ); ?>" name="<?php echo $this->get_field_name( 'cat_exclude' ); ?>" type="text" value="<?php echo esc_attr( $cat_exclude ); ?>" />
        <small>Comma separated list of category IDs to <strong>exclude</strong> in post query. e.g.: 1,16<br>If blank, no categories will be excluded.</small>
        </p>

        <p><input class="checkbox" type="checkbox" <?php checked( $vertical_sidebar_check, 'on' ); ?> id="<?php echo $this->get_field_id( 'vertical_sidebar_check' ); ?>" name="<?php echo $this->get_field_name( 'vertical_sidebar_check' ); ?>" />
        <label for="<?php echo $this->get_field_id( 'vertical_sidebar_check' ); ?>"><?php _e('Select for Vertical Sidebar', 'text-domain'); ?></label></p>


         <?php
    }

    public function update($new_instance, $old_instance) {
        $instance = $old_instance;
        $instance['title']           = sanitize_text_field( $new_instance['title'] );
        $instance['number_of_posts'] = absint( $new_instance['number_of_posts'] );
        $instance['number_of_words'] = absint( $new_instance['number_of_words'] );
        $instance['cat_include']     = sanitize_text_field( $new_instance['cat_include'] );
        $instance['cat_exclude']     = sanitize_text_field( $new_instance['cat_exclude'] );
        $instance[ 'vertical_sidebar_check' ] = isset( $new_instance[ 'vertical_sidebar_check' ] ) && ( 'on' === $new_instance[ 'vertical_sidebar_check' ] ) ? 'on' : 'off';
        return $instance;
    }

    public function widget($args, $instance) {
        extract( $args );

        $title = apply_filters( 'widget_title', $instance['title'], $instance, $this->id_base );

        echo $args['before_widget'];
        if ( $title ) {
            echo $args['before_title'] . $title . $args['after_title'];
        }

        $number_of_posts = ( ! empty( $instance['number_of_posts'] ) ) ? absint( $instance['number_of_posts'] ) : 5;
        if ( ! $number_of_posts ) {
            $number_of_posts = 5;
        }

        $number_of_words = ( ! empty( $instance['number_of_words'] ) ) ? absint( $instance['number_of_words'] ) : 20;
        if ( ! $number_of_words ) {
            $number_of_words = 20;
        }

        // Convert comma separated string to array for use in WP_Query.
        $category_include = $instance['cat_include'];
        if ( $category_include ) {
            $category_include = explode( ',', $instance['cat_include'] );
        } else {
            $category_include = array();
        }

        // Convert comma separated string to array for use in WP_Query.
        $category_exclude = $instance['cat_exclude'];
        if ( $category_exclude ) {
            $category_exclude = explode( ',', $instance['cat_exclude'] );
        } else {
            $category_exclude = array();
        }

        $vertical_sidebar_check = isset( $instance[ 'vertical_sidebar_check' ] ) && ( 'on' === $instance[ 'vertical_sidebar_check' ] ) ? 'on' : 'off';

        /* Create a custom query and get the most recent x projects. */
        $queryArgs = array(
            'category__in' => $category_include,
            'category__not_in' => $category_exclude,
            /* Order by date. */
            'orderby' => 'date',
            /* Show all posts. */
            'posts_per_page' => $number_of_posts,
        );

        $query = new WP_Query( $queryArgs );
        if ( $query->have_posts() ) : ?>
                <ul class="unbullet<?php echo $vertical_sidebar_check === 'on' ? ' unbullet-v' : ''; ?>">
                <?php while ( $query->have_posts() ) : $query->the_post(); ?>
                        <li class="snippet-box<?php echo $vertical_sidebar_check === 'on' ? ' vertical' : ''; ?>">
                            <div>
                                <!-- <img src="http://heightandweights.com/wp-content/uploads/2014/10/Beautiful-Lindsey-Vonn.jpg" alt="" class="hundred"> -->
                                <?php the_post_thumbnail( 'medium', array( 'class' => 'hundred' ) ); ?>
                                <div class="snippet-text">
                                    <h3><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3>
                                    <p><?php echo wp_trim_words( get_the_excerpt(), $number_of_words , __( '&hellip;', 'text_domain' ) ); ?></p>
                                </div>
                            </div>
                            <!-- <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail( 'large', array( 'class' => 'img-responsive' ) ); ?></a> -->
                        </li>
                <?php endwhile; ?>
                </ul>
        <?php endif;
        /* Display the markup after the widget. */
        echo $after_widget;
    }
}

add_action('widgets_init', function(){
    register_widget('chimp_post_widget');
});
  • Thank you so much, sir. Can't we get an arrangement in which we can get drop down options where category will have check boxes and the category that we will choose will be used in displaying posts in widgets? – The WP Novice May 7 '17 at 7:37
  • 1
    Happy to help, but this is as far as I can go for you on this question. What you are seeking is surely possible and it would be nice to have. However, the solution I've posted does solve the question as originally asked. You might get some more traction from other users on the site if you ask a new question and show your own coding efforts towards your goal if you get stuck along the way. Best of luck to you! – Dave Romsey May 7 '17 at 9:06
  • Deleted the duplicate question on stackexchange and accepted the solution here. – The WP Novice Mar 1 '18 at 19:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.