5

I am trying to create a custom Recent Posts widget that accepts a category, to show only posts in that category. I'm having trouble saving the widget options. I've done some debugging and found that in the update function, $new_instance only contains the title options and not via_cat. Here's the code for form and update:

    /**
     * Back-end widget form.
     *
     * @see WP_Widget::form()
     *
     * @param array $instance Previously saved values from database.
     */
    public function form($instance) {
        /* Set up some default widget settings. */
        $defaults = array( 'title' => '', 'via_cat' => 1);
        $instance = wp_parse_args( (array) $instance, $defaults );


        $cats = get_terms('category');
        $category_data = array();
        foreach ($cats as $cat) {
            $category_data[$cat->term_id] = $cat->name;
        }
?>
<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 esc_attr( $instance['title'] ); ?>" />
</p>
<p>
    <label for="<?php echo $this->get_field_id('via_cat'); ?>"><?php _e( 'Category:' ); ?></label>
    <select id="<?php echo $this->get_field_id('via_cat'); ?>" name="<?php echo $this->get_field_id('via_cat'); ?>">
<?php
        foreach ($category_data as $id => $name) {
?>
        <option value="<?php echo $id; ?>"<?php echo $instance['via_cat'] == $id ? ' selected="selected"' : ''; ?>><?php echo $name; ?></option>
<?php
        }
?>
    </select>
</p>
<?php
    }



/**
 * Sanitize widget form values as they are saved.
 *
 * @see WP_Widget::update()
 *
 * @param array $new_instance Values just sent to be saved.
 * @param array $old_instance Previously saved values from database.
 *
 * @return array Updated safe values to be saved.
 */
function update( $new_instance, $old_instance ) {
    $instance = $old_instance;
    $instance['title'] = strip_tags( $new_instance['title'] );
    $instance['via_cat'] = $new_instance['via_cat'];

    return $instance;
}

Any help is appreciated.

6

Your problem is that you're calling the wrong method for generating the name attribute. It should be $this->get_field_name('via_cat')

Also, you can use wp_dropdown_categories(), no need to reinvent the wheel:

wp_dropdown_categories(array(
  'name'      => $this->get_field_name('via_cat'),
  'selected'  => (int)$instance['via_cat'],
));

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.