0

I'm trying to use wp_dropdown_categories in a custom widget. Everything is displaying nicely but for some reason it's not saving properly.

Here are the form() and update() functions from my widget - am I doing something wrong?

public function form( $instance ) {

  /* Set up some default widget settings. */
  $defaults = array( 'title' => 'Classes by Category' );
  $instance = wp_parse_args( (array) $instance, $defaults ); ?>

  <!-- Widget Title -->
  <p>
    <label for="<?php echo $this->get_field_id( 'title' ); ?>">Title:</label>
    <input type="text" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" style="width:100%;" />
  </p>

  <!-- Categories Dropdown -->
  <p>
    <label for="<?php echo $this->get_field_id( 'cs-category' ); ?>">Choose Class Category:</label>

    <?php 
      $dropdown_args = array(
        'taxonomy' => 'cs_categories',
        'id' => $this->get_field_id( 'cs-category' ),
        'show_option_none' => __( 'Select category' ),
        'hide_empty' => true,
        'hierarchical' => true,
        'depth' => 2,
        'echo' => 0,
        'selected' => $instance[ 'cs-category' ],
        'class' => 'widefat'
      ); 

      echo wp_dropdown_categories( $dropdown_args );
    ?>
  </p>

  <?php
}

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

I'm assuming something is going wrong in the update() function, I'm not sure how to get the field to save.

I know I could use get_terms and a foreach loop to build the dropdown, but I want to use the build-in function because it handles hierarchical categories.

  • You haven't given it a name. – Jacob Peattie Feb 19 '18 at 11:47
1

You didn't add the dropdown/select name attribute, that's why it's not working as expected. Please try updating your $dropdown_args, here's the updated arguments -

$dropdown_args = array(
    'taxonomy'         => 'cs_categories',
    'id'               => $this->get_field_id( 'cs-category' ),
    'name'             => $this->get_field_name( 'cs-category' ), // Added this line
    'show_option_none' => __( 'Select category', 'text-domain' ),
    'hide_empty'       => true,
    'hierarchical'     => true,
    'depth'            => 2,
    'echo'             => 0,
    'selected'         => $instance[ 'cs-category' ],
    'class'            => 'widefat'
);

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.