HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Add user profile fields

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
userprofileaddfields

Problem

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?

Solution

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);

Code Snippets

/// 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);

Context

StackExchange Code Review Q#93917, answer score: 3

Revisions (0)

No revisions yet.