Support

Account

Home Forums General Issues Programmatic duplication Reply To: Programmatic duplication

  • Nevermind, ended up coding it myself (in this case, I want to clone a user’s meta). Code below for anyone else who might be interested:

    
    clone_user_meta(16,8);
            
    function clone_user_meta($source_user,$destination_user) {
        
        // check the users exist
        if(!user_exists($source_user) || !user_exists($destination_user)) { 
            return new WP_Error('whoops', __( "One of the specified users does not exist", 'my_textdomain' ));
        }
        
        // ignore any fields BEGINNING WITH
        $ignore_wildcard = array(
            'billing_',
            'shipping_',
        );
        
        // ignore specific FULLY NAMED fields
        $ignore = array(
            'nickname',
            'first_name',
            'last_name',
        );
    
        $source_meta = get_user_meta($source_user);
        
        foreach($source_meta as $key => $value) {
            
            // the current key is not in the $ignore list, continue
            if(!in_array($key, $ignore)) {
                
                $skip = false;
                
                // check if the current key matches a "wildcard ignore"
                foreach($ignore_wildcard as $wildcard_key) {
                    if(starts_with($wildcard_key,$key)) {
                       $skip = true; 
                       break; // we found one! break out of the loop
                    }
                }
                
                if(!$skip && $value[0] != '') { // valid field to clone
                    update_user_meta($destination_user,$key,$value); // add/update the value
                }
            }
        }
        
        return true;
    }
    
    function starts_with($needle, $haystack) {
        return strpos($haystack, $needle, 0)=== 0 ? true : false;
    }
    
    function user_exists($user_id) {
        $user = get_userdata($user_id);
        if ($user === false) {
            return false;
        }
        
        return true;
    }