• Hello,

    I am having a problem when saving an array into WordPress options. Basically, I have two different settings pages that will be saved into one database row as an array. These two different pages is registered using one register_setting() and two separate add_settings_section().

    In my sanitizing function, all data are saved correctly except one select element which accept multiple selections. It will be saved as multidimensional array in the one database row. Here is my code to save that array.

    public function sanitize_options( $input ) {
    
        $options = get_option( 'prfx_options' );
    
        if ( isset( $input['post_types'] ) && count( $input['post_types'] ) > 0 ) {
            $input['post_types'] = array_map( 'esc_attr', $input['post_types'] );
        } elseif {
            $input['post_types'] = array();
        }
    
        if ( is_array( $wpsdcp_options ) ) {
            return array_merge( $options, apply_filters( 'prfx_options_sanitization', $input ) );
    	} else {
    		return apply_filters( 'prfx_options_sanitization', $input );
    	}
    }

    It should accept 0 or more selections. It works fine when there’s at least one selection that is selected. But when there’s nothing that is selected, it won’t save it. I’ve tried count() and empty() but neither would work. Is there something wrong with my code?

    Thank you in advance!
    Mauris

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz

    (@bcworkz)

    array_key_exists ( 'post_types' , $input ) will distinguish between something selected and nothing selected, assuming $input is analogous to $_POST.

    I think the other problem is serializing an empty array. I haven’t verified it, but serializing an empty array may not save anything at all. You should try saving array("") which should serialize into an empty string instead of nothing. Naturally your processing code would need to account for the different representation of nothing.

    Thread Starter Yudhistira Mauris

    (@maurisrx)

    Thank you bcworkz for the answer. I’ve decided to make the settings page into one page, then I removed the isset logic for all inputs and it works well.

Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘Save array into WordPress options’ is closed to new replies.