4
\$\begingroup\$

I have this PHP function that adds custom user profile fields to WordPress. It saves the field through the WooCommerce form-edit-my-account.php file. I have a lot of repeated code, and would like to clean it up.

function save_sfirst_account_details( $user_ID ){
    $sfirst = ! empty( $_POST['sfirst'] ) ? wc_clean( $_POST['sfirst'] ) : '';
        update_user_meta( $user_ID, 'sfirst', $sfirst );
    }

function save_slast_account_details( $user_ID ){
    $slast = ! empty( $_POST['slast'] ) ? wc_clean( $_POST['slast'] ) : '';
    update_user_meta( $user_ID, 'slast', $slast );
}

function save_grade_account_details( $user_ID ){
    $grade = ! empty( $_POST['grade'] ) ? wc_clean( $_POST['grade'] ) : '';
    update_user_meta( $user_ID, 'grade', $grade);
}

function save_city_account_details( $user_ID ){
    $city = ! empty( $_POST['city'] ) ? wc_clean( $_POST['city'] ) : '';
    update_user_meta( $user_ID, 'city', $city );
}

function save_state_account_details( $user_ID ){
    $state = ! empty( $_POST['state'] ) ? wc_clean( $_POST['state'] ) : '';
    update_user_meta( $user_ID, 'state', $state);
}

function save_degree_account_details( $user_ID ){
    $degree = ! empty( $_POST['degree'] ) ? wc_clean( $_POST['degree'] ) : '';
    update_user_meta( $user_ID, 'degree', $degree );
}

function save_semail_account_details( $user_ID ){
    $semail = ! empty( $_POST['semail'] ) ? wc_clean( $_POST['semail'] ) : '';
    update_user_meta( $user_ID, 'semail', $semail );
}
add_action( 'woocommerce_save_account_details', 'save_student_account_details' );

Can anyone help me out with this?

\$\endgroup\$
  • \$\begingroup\$ Is there no way to make that one function that loops through the various "details" and then adds them all at once? What does the update_user_meta() do? \$\endgroup\$ – CodeX Jul 3 '15 at 11:40
  • \$\begingroup\$ You could build an array and pass that through the update_user_meta() function like this.. stackoverflow.com/questions/14872537/… \$\endgroup\$ – CodeX Jul 3 '15 at 11:43
3
\$\begingroup\$

I would make a single function, since all your functions do the same thing. It just needs an extra argument.

    /// one all-purpose function
    function saveData ($user_ID, $data_field) {
        $data = !empty($_POST[$data_field]) ? wc_clean($_POST[$data_field]) : '';
        update_user_meta( $user_ID, $data_field, $data );
    }

    /// define actions
    $actions=array("sfirst","slast",...);

    /// run actions
    foreach ($actions as $action) {
        add_action( 'woocommerce_save_account_details','saveData',$action);
    } unset($action);
\$\endgroup\$
  • 1
    \$\begingroup\$ The idea to use only one function and pass the parameter is good, why the downvote? \$\endgroup\$ – Marco Acierno Jul 18 '15 at 15:09

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.