0

I have this particular shortcode "[example]"

I know I can put this in a text widget to make it work.

But I was wondering about how I can turn this into a widget called "Example."

Any suggestion?

Thank you!

1

Simply create a new widget & register it -

/* Create a new Widget */
class WPSE180059_Widget extends WP_Widget 
{
    public function __construct()
    {
        $widget_ops = array(
            'classname' => 'widget_wpse180059', 
            'description' => __( 'A Custom Widget') 
        );
        parent::__construct('wpse180059', __('WPSE180059 Widget'), $widget_ops);
    }

    public function widget( $args, $instance )
    {
        $title = apply_filters( 
            'widget_title', 
             empty($instance['title']) ? '' : $instance['title'], 
             $instance, 
             $this->id_base 
        );

        echo $args['before_widget'];

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

        /* here goes your Shortcode */
        echo do_shortcode('[example]');

        echo $args['after_widget'];
    }

    public function update( $new_instance, $old_instance )
    {
        $instance['title'] = strip_tags($new_instance['title']);
        return $instance;
    }

    public function form( $instance )
    {
        //Defaults
        $title = esc_attr( $instance['title'] ); ?>
        <p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></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 $title; ?>" /></p>
<?php
    }
}

/* Register your Widget */
function WPSE180059_init() {
    register_widget('WPSE180059_Widget');
}
add_action('widgets_init', 'WPSE180059_init');
  • You are welcome. Once you have tested it, accept it as the correct answer :) – Shazzad Mar 3 '15 at 20:16
  • Thank you it worked. =) Just a minor question. My shortcode is the following : echo do_shortcode('[example title='sample']'); The problem is that when I put the "title='sample'", then it shows as a syntax error (or anything below this does not show as valid). It looks like the single quotation mark within the shortcode causes some problem. Would there be a way around it? (otherwise, the code works perfectly fine =) ) – steve Kim Mar 3 '15 at 21:06
  • ps. how do you mark it as a correct answer?? – steve Kim Mar 3 '15 at 21:07
  • Use double quote then - do_shortcode('[example title="sample"]'); or do_shortcode("[example title='sample']"); – Shazzad Mar 3 '15 at 21:10

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.