• Bbaale

    (@bbaale)


    Am coding a plugin which creates a wigdet where a user selects from the available categories but I don’t how to add selected() and how to check if user selected any option. Below is my code.

    <p>
    	<label for="<?php echo $this->get_field_id('select'); ?>"><?php _e('Select featured Category', 'wp_widget_plugin'); ?></label>
    	<select name="<?php echo $this->get_field_name('select'); ?>" id="<?php echo $this->get_field_id('select'); ?>" class="widefat">
     	<option value=""><?php echo esc_attr(__('Select Category')); ?></option>
     <?php
     $args = array('orderby' => 'name', 'parent' => 0 );
      $categories = get_categories($args);
      foreach ($categories as $category) {
      	$option = '<option value="'.$category->cat_ID.'">';
    	$option .= $category->cat_name;
    	$option .= ' ('.$category->category_count.')';
    	$option .= '</option>';
    	echo $option;
      }
     ?>
    	</select>
    </p>
Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz

    (@bcworkz)

    The initial <option> tag line should look something like this:
    $option = '<option value="'.$category->cat_ID.'" '.selected($stored_value[$this->get_field_name('select')], $category->cat_ID, false).'>';

    Assuming $stored_value[$this->get_field_name('select')] contains the stored value from a previous selection, then selected="selected" will be returned if that stored value is equal to $category->cat_ID. You get that value from the selection keyed by the <select> tag name, thus from either $_POST[$this->get_field_name('select')] or $_GET[$this->get_field_name('select')], depending on the form submission method.

    Thread Starter Bbaale

    (@bbaale)

    Thank you bcworkz I tried code, it worked and I think its more well formed than my.

    '<option value="'.$category->cat_ID.'" id="'.$category->cat_ID.'"', $select == $category->cat_ID ? ' selected="selected"' : '', '>', $category->cat_name, '</option>';

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘I need help on how to add selected()’ is closed to new replies.