-
-
Save dexit/00b408f6a08f27bd9b245ab1a59595fa to your computer and use it in GitHub Desktop.
Conditional category product with custom field input file (patentino) into Woocommerce page login and checkout - Array JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* File Upload @ WooCommerce My Account Registration | |
*/ | |
// -------------- | |
// 1. Add file input to register form | |
add_action( 'woocommerce_register_form', 'bbloomer_add_woo_account_registration_fields' ); | |
function bbloomer_add_woo_account_registration_fields() { ?> | |
<p class="form-row validate-required" id="image" data-priority=""><label for="image" class="">Inserire il patentino (JPG, PNG, PDF)<!--<abbr class="required" title="required">*</abbr> --></label><span class="woocommerce-input-wrapper"><input type='file' id='patentino' name='patentino' accept='image/*,.pdf'></span></p> | |
<?php | |
} | |
// -------------- | |
// 2. Validate new field | |
add_filter( 'woocommerce_registration_errors', 'bbloomer_validate_woo_account_registration_fields', 10, 3 ); | |
function bbloomer_validate_woo_account_registration_fields( $errors, $username, $email ) { | |
if ( isset( $_POST['patentino'] ) && empty( $_POST['patentino'] ) ) { | |
$errors->add( 'image_error', __( 'Perfavore, carica un file valido.', 'woocommerce' ) ); | |
} | |
return $errors; | |
} | |
// -------------- | |
// 3. Save new field | |
add_action( 'user_register', 'bbloomer_save_woo_account_registration_fields', 1 ); | |
function bbloomer_save_woo_account_registration_fields( $customer_id ) { | |
if ( isset( $_FILES['patentino'] ) ) { | |
require_once( ABSPATH . 'wp-admin/includes/image.php' ); | |
require_once( ABSPATH . 'wp-admin/includes/file.php' ); | |
require_once( ABSPATH . 'wp-admin/includes/media.php' ); | |
$attachment_id = media_handle_upload( 'patentino', 0 ); | |
if ( is_wp_error( $attachment_id ) ) { | |
update_user_meta( $customer_id, 'patentino', $_FILES['patentino'] . ": " . $attachment_id->get_error_message() ); | |
} else { | |
update_user_meta( $customer_id, 'patentino', $attachment_id ); | |
} | |
} | |
} | |
// -------------- | |
// 4. Add enctype to form to allow image upload | |
add_action( 'woocommerce_register_form_tag', 'bbloomer_enctype_custom_registration_forms' ); | |
function bbloomer_enctype_custom_registration_forms() { | |
echo 'enctype="multipart/form-data"'; | |
} | |
/* | |
* Show custom field into Order page and account editor | |
*/ | |
// -------------- | |
// 1. Show custom field user profile | |
function add_SaveImageField( $user ) { | |
//Code changes | |
$meta = get_the_author_meta( 'patentino', $user->ID ); | |
$patentino = wp_get_attachment_url( $meta ); | |
//EndCode changes | |
?> | |
<h3><?php _e('Patentino','woocommerce' ); ?></h3> | |
<table class="form-table"> | |
<tr> | |
<th><label for="save_patentino"><?php _e( 'Patentino', 'woocommerce' ); ?></label></th> | |
<td> | |
<!--Code changes--> | |
<?php if ( !empty($meta) ) { ?> | |
<a href="<?php echo $patentino ?>" class="button" target="_blank;">Visualizza Patentino</a> | |
<?php }else{ ?> | |
<h3>Patentino non caricato</h3> | |
<?php } ?> | |
<!--End Code changes--> | |
</td> | |
</tr> | |
</table> | |
<br /> | |
<?php | |
} | |
add_action( 'show_user_profile', 'add_SaveImageField', 10, 1 ); | |
add_action( 'edit_user_profile', 'add_SaveImageField', 10, 1 ); | |
// -------------- | |
// 2. Add columns into list order page | |
function patentino_account_number_column( $columns ) { | |
$columns['patentino'] = "Patentino"; | |
return $columns; | |
} | |
add_filter('manage_edit-shop_order_columns', 'patentino_account_number_column', 10, 1 ); | |
// -------------- | |
// 3. Populate columns custom field | |
function patentino_placeholder( $column, $post_id ) { | |
// Get order | |
$order = wc_get_order( $post_id ); | |
// Get user id | |
$user_id = $order->get_user_id(); | |
if( $column == 'patentino' ) { | |
$meta = get_user_meta( $user_id, 'patentino', true ); | |
$patentino = wp_get_attachment_url( $meta ); | |
// Value is found | |
if ( !empty($meta) ) { | |
echo '<a href='.$patentino.' class="button" target="_blank">Visualizza Patentino</a>'; | |
} else { | |
echo 'Nessun patentino caricato'; | |
} | |
} | |
} | |
add_filter( 'manage_shop_order_posts_custom_column', 'patentino_placeholder', 10, 2 ); | |
// -------------- | |
// 4. Show custom field into order data | |
add_action( 'woocommerce_admin_order_data_after_order_details', 'nolo_custom_field_display_cust_order_meta', 10, 1 ); | |
function nolo_custom_field_display_cust_order_meta($order){ | |
// Get user id | |
$user_id = $order->get_user_id(); | |
$meta = get_user_meta( $user_id, 'patentino', true ); | |
$patentino = wp_get_attachment_url( $meta ); | |
if ( !empty($meta) ) { | |
echo '<a href='.$patentino.' class="button" target="_blank" style="margin-top:20px;">Visualizza Patentino</a>'; | |
}else{ | |
echo '<div style="margin-top:50px;">Nessun patentino caricato</div>'; | |
} | |
} | |
/* ------------------------------------------------------------------------ */ | |
/** | |
* File Upload @ WooCommerce Checkout | |
*/ | |
// ------------------------ | |
// 1. Display field @ Checkout | |
add_action( 'woocommerce_checkout_before_customer_details', 'bbloomer_add_user_field_to_checkout' ); | |
function bbloomer_add_user_field_to_checkout( ) { | |
$user_id = get_current_user_id(); | |
$patentino = @json_decode(get_user_meta($user_id, 'patentino', true)); | |
$patentino = !$patentino ? '' : $patentino; | |
// HERE set the product category slug | |
$category = 'concimi'; | |
$found = $other = false; // Initializing variables | |
// Loop through cart items | |
foreach ( WC()->cart->get_cart() as $cart_item ) { | |
// checking for the specific product category | |
$term_slugs = wp_get_post_terms( $cart_item['product_id'], 'product_cat', array('fields' => 'slugs') ); | |
if( in_array($category, $term_slugs) ) { | |
$found = true; // Targeted product category found | |
} | |
elseif( ! in_array($category, $term_slugs) && sizeof($term_slugs) > 0 ){ | |
$other = true; // Other product categories found | |
} | |
} | |
// If the targeted product category is mixed with other product categories | |
if ( !$found || $found && $other ) { | |
?> | |
<div id="my_custom_checkout_field"><h2 style="text-transform:uppercase;">Carica il patentino</h2> | |
<img id="immagine" onerror="this.onerror=null; this.src='/wp-content/uploads/2022/05/E2E2E2.png'" src="<?php echo $patentino->thumb; ?>"/> | |
<div> | |
<div class="file-upload btn btn-style-default btn-style-round btn-color-primary btn-icon-pos-right"> | |
<span id="carica-pentino">Carica Patentino</span> | |
<input id="patentino" type="file" data-ajaxed="Y" name="patentino" class="upload" accept='image/*,.pdf'/> | |
<input type="hidden" name="image_aid" value="" /> | |
</div> | |
</div> | |
</div> | |
<style> | |
#immagine { | |
display: inline-block; | |
width: 150px; | |
height: 150px; | |
overflow: hidden; | |
background: #e2e2e2; | |
border: 1px solid #cdcdcd; | |
line-height: 120px; | |
margin-bottom: 10px; | |
} | |
.file-upload input.upload { | |
position: absolute; | |
top: 0; | |
right: 0; | |
margin: 0; | |
padding: 0; | |
font-size: 20px; | |
cursor: pointer; | |
opacity: 0; | |
filter: alpha(opacity=0); | |
} | |
</style> | |
<script> | |
(function($){ | |
$('input[type=file][data-ajaxed=Y]').on('change', function(event) { | |
files = event.target.files; | |
var cont = $(this).attr('data-cont'); | |
var name = $(this).attr('name'); | |
var data = new FormData(); | |
var ext = this.value.match(/\.(.+)$/)[1]; | |
switch (ext) { | |
case 'jpg': | |
case 'jpeg': | |
case 'png': | |
case 'pdf': | |
break; | |
default: | |
alert('Questo tipo di file non è consentito!'); | |
this.value = ''; | |
$("#carica-pentino").text("Carica un'altro tipo di file"); | |
} | |
// Check size file | |
if(this.files[0].size > 2097152){ | |
//alert(this.files[0].size); | |
alert('Il file caricato è troppo grande! Carica un file fino a 2MB'); | |
this.value = ''; | |
$("#carica-pentino").text("Comprimi il file e riprova"); | |
return; | |
} | |
$.each(files, function(key, value) | |
{ | |
data.append(key, value); | |
}); | |
data.append('type', $(this).data('type')); | |
//$(cont).html('<img src="/wp-content/uploads/2022/05/Reload-1s-200px.svg" />'); | |
$('#immagine').attr('src', '/wp-content/uploads/2022/05/Reload-1s-200px.svg'); | |
$.ajax({ | |
url: '/wp-admin/admin-ajax.php?action=file_upload&fname='+name, // Url to which the request is send | |
method: "POST", // Type of request to be send, called as method | |
data: data, // Data sent to server, a set of key/value pairs (i.e. form fields and values) | |
dataType: 'json', | |
contentType: false, // The content type used when sending data to the server. | |
cache: false, // To unable request pages to be cached | |
processData:false, // To send DOMDocument or non processed data file it is set to false | |
success: function(data) // A function to be called if request succeeds | |
{ | |
console.log(data); | |
if(data.error) | |
{ | |
alert(data.error); | |
} | |
else | |
{ | |
$('#immagine').attr('src', data.src + '?_=' + new Date().getTime()); | |
$('[name='+name+'_aid]').val(data.aid); | |
$("#carica-pentino").text("File Caricato con successo"); | |
} | |
}, | |
error: function(jqXHR, textStatus, errorThrown) | |
{ | |
// Handle errors here | |
console.log('ERRORS: ' + textStatus); | |
alert('ERRORS: ' + textStatus); | |
$(cont).html('error'); | |
// STOP LOADING SPINNER | |
} | |
}); | |
}); | |
})(jQuery); | |
</script> | |
<?php | |
//} | |
} | |
} | |
// ------------------------ | |
// 2. Save field @ Checkout | |
add_action('wp_ajax_nopriv_file_upload', 'dg_file_upload_handler'); | |
add_action('wp_ajax_file_upload', 'dg_file_upload_handler'); | |
function dg_file_upload_handler() | |
{ | |
//Get the file | |
$f = 0; | |
$_FILES[$f] = $_FILES[0]; | |
$user = new WP_User(get_current_user_id()); | |
$json['status'] = 'error'; | |
//Check if the file is available && the user is logged in | |
if (!empty($_FILES[$f]) && $user->ID > 0) { | |
$json = array(); | |
require_once(ABSPATH . 'wp-admin/includes/image.php'); | |
require_once(ABSPATH . 'wp-admin/includes/file.php'); | |
require_once(ABSPATH . 'wp-admin/includes/media.php'); | |
//Handle the media upload using WordPress helper functions | |
$attachment_id = media_handle_upload($f, 0); | |
$json['aid'] = $attachment_id; | |
//If error | |
if (is_wp_error($attachment_id)) { | |
$json['error'] = "Error."; | |
} else{ | |
//delete current | |
$patentino = get_user_meta($user->ID, 'patentino', true); | |
if ($patentino) { | |
$patentino = json_decode($patentino); | |
if (isset($patentino->attachment_id)) { | |
wp_delete_attachment($patentino->attachment_id, true); | |
} | |
} | |
//Generate attachment in the media library | |
$attachment_file_path = get_attached_file($attachment_id); | |
$data = wp_generate_attachment_metadata($attachment_id, $attachment_file_path); | |
//Get the attachment entry in media library | |
$image_full_attributes = wp_get_attachment_image_src($attachment_id, 'full'); | |
$image_thumb_attributes = wp_get_attachment_image_src($attachment_id, 'smallthumb'); | |
$arr = array( | |
'attachment_id' => $attachment_id, | |
'url' => $image_full_attributes[0], | |
'thumb' => $image_thumb_attributes[0] | |
); | |
//Save the image in the user metadata | |
update_user_meta($user->ID, 'patentino', json_encode($arr)); | |
$json['src'] = $arr['thumb']; | |
$json['status'] = 'ok'; | |
} | |
} | |
//Output the json | |
die(json_encode($json)); | |
} | |
// ------------------------ | |
// 3. Validate new field | |
add_action( 'woocommerce_after_checkout_validation', 'shipping_time_optionss', 9999, 2); | |
function shipping_time_optionss( $fields, $errors ){ | |
$user_id = get_current_user_id(); | |
$patentino = @json_decode(get_user_meta($user_id, 'patentino', true)); | |
// if any validation errors | |
if ( empty( $patentino ) ) { | |
$errors->add( 'woocommerce_patentino_error', __( '<strong>Carica patentino</strong> è un campo obbligatorio.' ) ); | |
} | |
} | |
/* ----- */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment