0

I'm creating a widget, and I'm displaying categories list in form function:

echo '<select name="categories">';
  // Add custom option as default
  echo '<option>' . __('No Category', 'text-domain') . '</option>';

  // Get categories as array
  $categories = get_categories( $args );
  foreach ( $categories as $category ) :

    // Check if current term ID is equal to term ID stored in database
    $selected = ( $stored_category_id ==  $category->term_id  ) ? 'selected' : '';

    echo '<option value="' . $category->term_id . '" ' . $selected . '>' . $category->name . '</option>';

  endforeach;

echo '</select>';

So I want to display the selected category name in front-end, what code should I use in widget function:

Your selected category is:

0

You need to save your selection and then call that selected value into your widget() method.

Here is an example of what I mean which displays the selected category name and description in the front end. You can use this widget as a base for your own widget. Just a note, this widget requires at least PHP 5.4

/**
 * Select_Category widget class
 *
 * Display a selected category
 *
 * @since 1.0.0
*/
class Select_Category extends WP_Widget 
{

    public function __construct() 
    {
        parent::__construct(
            'widget_selected_category', 
            _x( 'Selected Category Widget', 'Selected Category Widget' ), 
            [ 'description' => __( 'Display a selected category.' ) ] 
        );
        $this->alt_option_name = 'widget_selected_category';

        add_action( 'save_post', [$this, 'flush_widget_cache'] );
        add_action( 'deleted_post', [$this, 'flush_widget_cache'] );
        add_action( 'switch_theme', [$this, 'flush_widget_cache'] );
    }

    public function widget( $args, $instance ) 
    {
        $cache = [];
        if ( ! $this->is_preview() ) {
            $cache = wp_cache_get( 'widget_selected_cat', 'widget' );
        }

        if ( ! is_array( $cache ) ) {
            $cache = [];
        }

        if ( ! isset( $args['widget_id'] ) ) {
            $args['widget_id'] = $this->id;
        }

        if ( isset( $cache[ $args['widget_id'] ] ) ) {
            echo $cache[ $args['widget_id'] ];
            return;
        }

        ob_start();

        $title          = ( ! empty( $instance['title'] ) ) ? $instance['title'] : __( 'Category Posts' );
        /** This filter is documented in wp-includes/default-widgets.php */
        $title          = apply_filters( 'widget_title', $title, $instance, $this->id_base );
        if ( ! $number ) {
            $number = 5;
        }
        $cat_id       = $instance['cat_id'];


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

        $select_cat_object = get_category( $cat_id );
        echo 'Your selected category is ' . $select_cat_object->name;
        echo "\n\t";
        echo $select_cat_object->description;

        echo $args['after_widget']; 

        if ( ! $this->is_preview() ) {
            $cache[ $args['widget_id'] ] = ob_get_flush();
            wp_cache_set( 'widget_selected_cat', $cache, 'widget' );
        } else {
            ob_end_flush();
        }
    }

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

        $this->flush_widget_cache();

        $alloptions = wp_cache_get( 'alloptions', 'options' );
        if ( isset($alloptions['widget_selected_category']) )
            delete_option('widget_selected_category');

        return $instance;
    }

    public function flush_widget_cache() 
    {
        wp_cache_delete('widget_selected_cat', 'widget');
    }

    public function form( $instance ) 
    {

        $title  = isset( $instance['title'] ) ? esc_attr( $instance['title'] ) : '';
        $cat_id = isset( $instance['cat_id'] ) ? absint( $instance['cat_id'] ) : 1;
        ?>

        <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>

        <p>
            <label for="<?php echo $this->get_field_id('cat_id'); ?>"><?php _e( 'Category Name:' )?></label>
            <select id="<?php echo $this->get_field_id('cat_id'); ?>" name="<?php echo $this->get_field_name('cat_id'); ?>">
                <?php 
                $this->categories = get_categories();
                foreach ( $this->categories as $cat ) {
                    $selected = ( $cat->term_id == esc_attr( $cat_id ) ) ? ' selected = "selected" ' : '';
                    $option = '<option '.$selected .'value="' . $cat->term_id;
                    $option = $option .'">';
                    $option = $option .$cat->name;
                    $option = $option .'</option>';
                    echo $option;
                }
                ?>
            </select>
        </p>

    <?php
    }

}

add_action( 'widgets_init', function () 
{
    register_widget( 'Select_Category' );
});

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.