0

Currently I am doing

    public function prfx_meta_save ($post_id){

    if (isset( $_POST[ 'firstname'])){
        update_post_meta($post_id, 'firstname', $_POST[ 'firstname']);
    }
    if (isset( $_POST[ 'lastname'])){
        update_post_meta($post_id, 'lastname', $_POST[ 'lastname']);
    }
    if (isset( $_POST[ 'sex'])){
        update_post_meta($post_id, 'sex', $_POST[ 'sex']);
    }
}

But I would like to somehow loop over all the post values (Not just the ones here) and save them all. So if I add more fields to my Meta Box it should save them without me having to add another update_post_meta

Thanks for the help

2

1 Answer 1

1

I would suggest you define a field names property on your class:

class your_class {
    private $_fields = array(
        'firstname',
        'lastname',
        'sex',
    );

    public function prfx_meta_save ( $post_id ) {

    }
}

Now you can fully abstract your save handler:

foreach ( $this->_fields as $field ) {
    if ( ! isset( $_POST[ $field ] ) )
        continue;

    $value = ( string ) $_POST[ $field ];
    $value = wp_unslash( $value ); // WP adds slashes to all request data
    $value = sanitize_text_field( $value ); // Fix invalid UTF-8, strip tags & line breaks

    update_post_meta( $post_id, $field, $value );
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.