· 4 years ago · May 06, 2021, 05:22 AM
1<?php
2// Displaying the custom attributes in cart and checkout items
3//add_filter( 'woocommerce_get_item_data', 'customizing_cart_item_data', 20, 2 );
4function customizing_cart_item_data( $cart_data, $cart_item ) {
5 $custom_items = array();
6 if( ! empty( $cart_data ) ) $custom_items = $cart_data;
7
8 // Get the data (custom attributes) and set them
9 /*if( ! empty( $cart_item['custom_data']['attribute_pa_cor'] ) )
10 $custom_items[] = array(
11 'name' => 'attribute_pa_cor',
12 'value' => $cart_item['custom_data']['attribute_pa_cor'],
13 );*/
14
15 if( ! empty( $cart_item['custom_data']['attribute_pa_fusao'] ) )
16 $custom_items[] = array(
17 'name' => 'Fusão',
18 'value' => $cart_item['custom_data']['attribute_pa_fusao'],
19 );
20
21 //print_r($cart_item);
22 return $custom_items;
23}
24
25// Store the custom data to cart object/*
26
27//add_filter( 'woocommerce_add_cart_item_data', 'save_custom_product_data', 20, 2 );
28function save_custom_product_data( $cart_item_data, $product_id ) {
29 $bool = false;
30 $data = array();
31 /*if( isset( $_REQUEST['attribute_pa_cor'] ) ) {
32 $cart_item_data['custom_data']['attribute_pa_cor'] = $_REQUEST['attribute_pa_cor'];
33 $data['attribute_pa_cor'] = $_REQUEST['attribute_pa_cor'];
34 $bool = true;
35 }*/
36
37 if( isset( $_REQUEST['attribute_pa_fusao'] ) ) {
38 $cart_item_data['attribute_pa_fusao'] = $_REQUEST['attribute_pa_fusao'];
39 $data['attribute_pa_fusao'] = $_REQUEST['attribute_pa_fusao'] . "-09-";
40 $bool = true;
41 }
42
43 if($bool){
44 // below statement make sure every add to cart action as unique line item
45 $cart_item_data['custom_data']['unique_key'] = md5( microtime().rand() );
46 WC()->session->set( 'custom_variations', $data );
47 }
48 return $cart_item_data;
49}
50
51//add_filter('woocommerce_dropdown_variation_attribute_options_args','fun_select_default_option',10,1);
52function fun_select_default_option( $args)
53{
54 //print_r($args);
55 if(count($args['options']) > 0) //Check the count of available options in dropdown
56 $args['selected'] = $args['options'][0];
57 return $args;
58}
59
60// Removes Woocommerce You cannot add another product to your cart massage
61//add_filter( 'woocommerce_cart_product_cannot_add_another_message', '__return_false' );
62/*
63function customize_wc_errors( $error ) {
64 if ( strpos( $error, 'entfernt' ) !== false ) {
65 return '';
66 } elseif ( strpos( $error, 'removed' ) !== false ) {
67 return '';
68 } else {
69 return $error;
70 }
71}*/
72//add_filter( 'woocommerce_add_error', 'customize_wc_errors' );
73//add_filter( 'wc_add_to_cart_message_html', '__return_false' );
74
75
76//add_action( 'woocommerce_before_calculate_totals', 'wc_auto_add_gift_to_cart' );
77function wc_auto_add_gift_to_cart( $cart ) {
78 if (is_admin() && !defined('DOING_AJAX'))
79 return;
80
81 $required_product_id = 6906; // The required product Id (or variation Id)
82 $parent_gift_id = 6724; // The parent variable product Id (gift) for a product variation (set to zero for simple products)
83 $product_gift_id = 6906; // the variation Id or the product Id (gift)
84
85 $has_required = $gift_key = false; // Initializing
86
87 foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
88 // Check if required product is in cart
89 if( in_array( $required_product_id, array($cart_item['product_id'], $cart_item['variation_id']) ) ) {
90 $has_required = true;
91 }
92
93 //Check if gifted product is already in cart
94
95 //$term_slug = get_term_by('name', $term_name='attribute_pa_cor', $taxonomy )->slug;
96
97 if( $cart_item['data']->get_id() == $product_gift_id ) {
98 $gift_key = $cart_item_key;
99
100 }
101 }
102
103 //$result = get_post_meta(1707, 'attribute_pa_cor', true );
104 $isFusao = false;
105 $chave = array_keys($cart->get_cart());
106 //var_dump($chave);
107
108 //$product = new WC_Product_Variation(1712);
109 //$product->set_visible(false);
110 //var_dump($product->get_attribute());
111
112 foreach($cart->get_cart() as $a=>$variations){
113 //print_r($cart->get_cart()[$chave[0]]['variation'][$k]);
114 foreach($variations['variation'] as $b=>$attribute){
115
116 if($b == 'attribute_pa_fusao'){
117 $isFusao = true;
118 //echo "fusao existe: " . $attribute . "<br>";
119 //echo '<style>.variation-Cor{ display: none !important;}</style>';
120
121 //add_action('wp_head', 'my_custom_styles', 100);
122 //ul.variation li {display: none !important;}
123 //wp_register_style( 'dummy-handle', false );
124 //wp_enqueue_style( 'dummy-handle' );
125 //wp_add_inline_style( 'dummy-handle',
126 //'li.variation-Cor{ display: none !important;}' );
127
128
129
130 }else{
131 // echo "fusao não existe: " . $attribute . " [{$b}]<br>";
132 }
133
134 if($b == "attribute_pa_cor"){
135
136 if($isFusao){
137 //echo "excluindo attributo $attribute [{$b}] <br>";
138 }else{
139 //echo "não foi excluido attributo $attribute [{$b}]<br>";
140 }
141
142 //$cart->get_cart()[$chave[0]]['variation'][$k] = "null";
143 /*
144 if($cart->remove_cart_item($kc)){
145 echo "removido com sucesso<br>";
146 }else{
147 echo "errrou<br>";
148 }*/
149 //variation-Cor
150 }
151 }
152 }
153
154
155 //print_r($cart->get_cart());
156
157 //var_dump($result);
158
159 $variation_ids_in_cart = array();
160
161 //Loop through cart items
162 foreach( WC()->cart->get_cart() as $cart_item ) {
163 $variation_ids_in_cart[] = $cart_item['variation_id'];
164 }
165
166 foreach($variation_ids_in_cart as $v=>$variation_id){
167 //$variation_id
168 }
169
170 // Only if a variation ID for this variable product is in cart
171 //print_r($variation_ids_in_cart);
172 if( sizeof($variation_ids_in_cart) == 0 ) return; // Exit
173
174
175 // If gift is in cart, but not the required product: Remove gift from cart
176 if ( ! $has_required && $gift_key ) {
177 //echo "remove gift key";
178 $cart->remove_cart_item( $gift_key );
179 }
180 // If gift is not in cart and the required product is in cart: Add gift to cart
181 elseif ( $has_required && ! $gift_key ) {
182 // For simple products
183 //echo "aq";
184 if( $parent_gift_id == 0 ) {
185 $cart->add_to_cart( $product_gift_id );
186 }
187 // For product variations (of a variable product)
188 else {
189 $cart->add_to_cart( $parent_gift_id, 1, $product_gift_id );
190 //print_r($product_gift_id);
191 }
192 }else{
193 //echo "aq";
194 //$cart->add_to_cart( $parent_gift_id, 1, $product_gift_id );
195 }
196}
197
198//add_filter('woocommerce_reset_variations_link', '__return_empty_string');
199
200
201
202//add_filter( 'woocommerce_variation_is_active', 'bbloomer_grey_out_variations_out_of_stock', 10, 2 );
203
204function bbloomer_grey_out_variations_out_of_stock( $is_active, $variation ) {
205 if ( ! $variation->is_in_stock() ) return false;
206 return $is_active;
207}
208
209add_filter( 'woocommerce_variation_is_active', 'grey_out_variations_when_out_of_stock', 10, 2 );
210
211function grey_out_variations_when_out_of_stock( $grey_out, $variation ) {
212 //print_r($variation->is_in_stock());
213 if ( ! $variation->is_in_stock() )
214 return false;
215
216 return true;
217}
218
219//add_filter('woocommerce_swatches_get_swatch_anchor_css_class', 'add_swatch_out_stock_class', 10, 2);
220
221function add_swatch_out_stock_class( $anchor_classes, $swatch_term ) {
222 if ( is_product() ) {
223 global $post;
224 $product = wc_get_product($post);
225
226 if ( $product->get_type() === 'variable' ) {
227 foreach( $product->get_available_variations() as $variation ) {
228 $product_variation = new WC_Product_Variation($variation['variation_id']);
229
230 if( $product_variation->get_stock_quantity() === 0 ) {
231 foreach( $product_variation->get_variation_attributes() as $var_attribute) {
232 if( $swatch_term->term_slug === $var_attribute) {
233 $anchor_classes .= ' out-of-stock';
234 }
235 }
236 }
237 }
238 }
239 }
240 return $anchor_classes;
241}
242
243add_filter( 'woocommerce_sale_flash', 'wooc_custom_replace_sale_text',99,3);
244function wooc_custom_replace_sale_text( $html,$post, $product) {
245 //print_r($html);
246 return str_replace( __( 'Sale!', 'woocommerce' ), __( 'Your Text', 'woocommerce' ), $html );
247}
248
249
250add_filter( "woocommerce_checkout_fields", "reordering_custom_default_email_field", 15, 1 );
251
252function reordering_custom_default_email_field($fields){
253 $fields['billing']['billing_email']['priority'] = 1;
254 return $fields;
255}
256
257$fields['billing']['billing_email']['priority'] = 10;
258/*
259add_filter( 'woocommerce_default_address_fields', 'custom_override_default_locale_fields' );
260function custom_override_default_locale_fields( $fields ) {
261 $fields['billing_first_name']['priority'] = 20;
262 $fields['billing_last_name']['priority'] = 30;
263 $fields['billing_persontype']['priority'] = 40;
264 $fields['billing_cpf']['priority'] = 50;
265 $fields['billing_country']['priority'] = 60;
266 $fields['billing_postcode']['priority'] = 70;
267 $fields['billing_company']['priority'] = 80;
268 $fields['billing_cnpj']['priority'] = 90;
269 $fields['billing_address_1']['priority'] = 100;
270 $fields['billing_number']['priority'] = 110;
271 $fields['billing_address_2']['priority'] = 120;
272 $fields['billing_neighborhood']['priority'] = 130;
273 $fields['billing_city']['priority'] = 140;
274 $fields['billing_state']['priority'] = 150;
275 $fields['billing_phone']['priority'] = 160;
276 $fields['billing_cellphone']['priority'] = 170;
277
278 return $fields;
279}
280*/
281function my_wc_custom_checkout_billing_fields($fields) {
282 $fields['billing_neighborhood']['required'] = true;
283
284 return $fields;
285}
286
287add_filter('woocommerce_billing_fields', 'my_wc_custom_checkout_billing_fields',20);
288/*
289add_filter( 'woocommerce_checkout_fields' , 'onblur_postcode' );
290function onblur_postcode( $fields ) {
291
292 $fields['billing']['billing_postcode']['onblur'] = 'onblur="pesquisacep(this.value);"';
293 return $fields;
294}*/
295
296
297
298 /**
299 * Regular user
300 */
301
302function my_account_menu_order() {
303 $menuOrder = array(
304 'dashboard' => __( 'Painel', 'woocommerce' ),
305 'orders' => __( 'Pedidos', 'woocommerce' ),
306 'edit-address' => __( 'Endereços', 'woocommerce' ),
307 'edit-account' => __( 'Detalhes da Conta', 'woocommerce' ),
308 'customer-logout' => __( 'Sair', 'woocommerce' ),
309 );
310 return $menuOrder;
311 }
312
313 add_filter ( 'woocommerce_account_menu_items', 'my_account_menu_order' );
314
315
316 /*
317 **
318 * Register new endpoints to use inside My Account page.
319 */
320
321$user = wp_get_current_user();
322$allowed_roles = array('subscriber', 'administrator','lojista','lojista3','lojista10','lojista15',
323'cpa', 'cpa3','cpa10','cpa15');
324
325if( array_intersect($allowed_roles, $user->roles ) ) {
326
327
328 function my_account_menu_order_varej(){
329 $menuOrder = array(
330 'dashboard' => __( 'Painel', 'woocommerce' ),
331 'orders' => __( 'Pedidos', 'woocommerce' ),
332 'Lojista' => __( 'Produtos', 'woocommerce' ),
333 'Documentos' => __( 'Documentos', 'woocommerce' ),
334 'edit-address' => __( 'Endereços', 'woocommerce' ),
335 'edit-account' => __( 'Detalhes da Conta', 'woocommerce' ),
336 'customer-logout' => __( 'Sair', 'woocommerce' ),
337 );
338 return $menuOrder;
339 }
340
341add_filter ( 'woocommerce_account_menu_items', 'my_account_menu_order_varej' );
342
343//lembrar de atualizar os permalinks em configurações pois é necessários pois há cache do wp
344add_action( 'init', 'my_account_new_endpoints' );
345add_action( 'init', 'my_account_new_endpoints_documentos' );
346
347 function my_account_new_endpoints() {
348 flush_rewrite_rules();
349 add_rewrite_endpoint( 'Lojista', EP_ROOT | EP_PAGES );
350
351 }
352
353 function my_account_new_endpoints_documentos() {
354 flush_rewrite_rules();
355 add_rewrite_endpoint( 'Documentos', EP_ROOT | EP_PAGES );
356
357 }
358 /**
359 * Get new endpoint content
360 */
361
362 // Awards
363 add_action( 'woocommerce_account_Lojista_endpoint', 'Lojista_endpoint_content' );
364 function Lojista_endpoint_content() {
365 flush_rewrite_rules();
366 get_template_part('Lojista');
367 }
368
369
370 // Awards
371 add_action( 'woocommerce_account_Documentos_endpoint', 'Documentos_endpoint_content' );
372 function Documentos_endpoint_content() {
373 flush_rewrite_rules();
374 get_template_part('Documentos');
375 }
376}
377
378
379//add_filter( 'get_terms', 'ts_get_subcategory_terms', 10, 3 );
380function ts_get_subcategory_terms($terms, $taxonomies, $args){
381 $user = wp_get_current_user();
382 $allowed_roles = array('subscriber', 'administrator');
383 $new_terms = array();
384 // if it is a product category and on the shop page
385 if (in_array('product_cat', $taxonomies) && ! is_admin() && is_shop()
386 && ! array_intersect($allowed_roles, $user->roles )) {
387 foreach( $terms as $key => $term ) {
388 if ( !in_array( $term->slug, array( 'lojista' ) ) ) { //pass the slug name here
389 $new_terms[] = $term;
390 }
391 }
392 $terms = $new_terms;
393 }
394 return $terms;
395 }
396
397
398add_shortcode ('BannerVarejista', 'banner_varejista_shortcode');
399
400function banner_varejista_shortcode($atts) {
401 $user = wp_get_current_user();
402 $allowed_roles = array('subscriber', 'administrator',"fornecedor");
403 if(!array_intersect($allowed_roles, $user->roles)){
404 return false;
405 }
406 else{
407 echo do_shortcode('[rev_slider alias="banner-principal"]');
408 }
409
410}
411
412/**
413 * Add custom data to WC API shop order response
414 * Overriding "$object" here with $order so it's easier to access its properties
415 */
416/*function my_wc_rest_prepare_order( $response, $order, $request ) {
417 setlocale(LC_TIME, 'pt_BR', 'pt_BR.utf-8', 'pt_BR.utf-8', 'portuguese');
418 date_default_timezone_set('America/Sao_Paulo');
419 $timecreated = strftime('%A, %d de %B de %Y', strtotime('today'));
420 if( empty( $response->data ) )
421 return $response;
422
423 $order_id = $order->get_id();
424
425 // Get an instance of the WC_Order object
426 $order = wc_get_order($order_id);
427
428 // Get the user ID from WC_Order methods
429 $user_id = $order->get_customer_id(); // $order->get_user_id(); // or $order->get_customer_id();
430
431 // check for WooCommerce Social Login User Avatar
432 if( class_exists( 'WC_Social_Login' ) ) {
433
434 $fb_avatar = get_user_meta( $user_id, '_wc_social_login_facebook_profile_image', true );
435 $gplus_avatar = get_user_meta( $user_id, '_wc_social_login_google_profile_image', true );
436
437 }
438
439 $social_data = array();
440 $avatar_url = array();
441
442 $customer_picture = array(
443 'default' => get_avatar_url( $user_id ),
444 'facebook' => ( $fb_avatar ) ? esc_url( $fb_avatar ) : '',
445 'google' => ( $gplus_avatar ) ? esc_url( $gplus_avatar ) : ''
446 );
447
448 if(is_rest()){
449 $response->data['meta_data'][0] = ['key'=>'user_rest_request', 'value'=>'ciro'];
450 $response->data['meta_data'][1] = ['key'=>'rest_modification_date', 'value'=>$timecreated];
451
452 }
453 return $response;
454}
455
456add_filter( 'woocommerce_rest_prepare_shop_order_object', 'my_wc_rest_prepare_order', 10, 3 );
457
458*/
459/*
460
461function your_prefix_on_insert_rest_api( $object, $request, $is_creating ) {
462 if ( ! $is_creating ) {
463 return;
464 }
465
466 $order_id = $object->get_id();
467 $wc_order = new WC_Order( $order_id );
468 $wc_order->update_status('awaiting-shipment');
469
470 do_action( 'woocommerce_new_order', $order_id, $wc_order );
471}
472
473add_action( "woocommerce_rest_insert_shop_order_object", 'your_prefix_on_insert_rest_api', 10, 3 );*/
474
475//sempre que um status for alterado | registra qual usuário efetuou a operação
476/*
477add_action('woocommerce_order_status_changed', 'order_confirmation',10, 1);
478function order_confirmation($order_id){
479
480 $wc_order = new WC_Order($order_id);
481 $wc_order->update_status('completed');
482 do_action( 'woocommerce_new_order', $order_id, $wc_order );
483 update_post_meta( $order_id, 'user_altered', sanitize_text_field('user_altered'));
484 error_log( print_r( 'Works???', true ) );
485}
486*/
487
488//add_action('woocommerce_new_order', 'order_confirmation',10,1);
489
490//sempre que um pedido for inserido | registra quem efetuou a operação
491
492//sempre que um pedido for alterado | registra quem efetuou a operação
493
494
495
496// define the woocommerce_api_create_order callback
497/*
498function action_woocommerce_api_create_order( $order_get_id, $data, $instance ) {
499 // make action magic happen here...
500 $wc_order = new WC_Order($order_id);
501 $wc_order->update_status('completed');
502 do_action( 'woocommerce_new_order', $order_id, $wc_order );
503 update_post_meta( $order_id, 'user_altered', sanitize_text_field('user_altered'));
504 error_log( print_r( 'Works???', true ) );
505}
506 */
507// add the action
508#add_action( 'woocommerce_api_create_order', 'action_woocommerce_api_create_order', 10, 3 );
509
510
511
512
513/*
514add_filter( 'rest_pre_echo_response', function( $response, $object, $request ) {
515 setlocale(LC_TIME, 'pt_BR', 'pt_BR.utf-8', 'pt_BR.utf-8', 'portuguese');
516 date_default_timezone_set('America/Sao_Paulo');
517 $timecreated = strftime('%A, %d de %B de %Y', strtotime('today'));
518
519 $order_id = $response['id'];
520 $wc_order = new WC_Order($order_id);
521 //$wc_order->set_order_key("1235481-XML");
522 if(!$wc_order->meta_exists('rest_admin_user') && !$wc_order->meta_exists('rest_modification_date')){
523 $wc_order->add_meta_data('rest_admin_user','Ciro');
524 $wc_order->add_meta_data('rest_modification_date',$timecreated);
525
526 }
527
528
529 //do_action( 'woocommerce_new_order', $order_id, $wc_order );
530 //update_post_meta( $order_id, 'user_altered', sanitize_text_field('user_altered'));
531 $wc_order->save();
532 //$wc_orderData->save();
533 //criamos o arquivo
534 //$arquivo = fopen('meuarquivo.txt','w');
535 //verificamos se foi criado
536 //if ($arquivo == false) die('Não foi possível criar o arquivo.');
537 //escrevemos no arquivo
538 //$texto = $response['id'] . " + " . $atualizou;
539 //fwrite($arquivo, $texto);
540 //Fechamos o arquivo após escrever nele
541 if(is_rest()){
542 $response->data['meta_data']['key'] = 'user_rest_request';
543 $response->data['meta_data']['value'] = 'Ciro';
544 $response->data['meta_data']['key'] = 'rest_modification_date';
545 $response->data['meta_data']['value'] = $timecreated;
546
547 }
548 //fclose($arquivo);
549 return $response;
550}, 10, 3 );
551
552*/
553
554
555//add_filter( 'manage_users_columns', 'column_register_wpse_101322' );
556//add_filter( 'manage_users_custom_column', 'column_display_wpse_101322', 10, 3 );
557
558function column_register_wpse_101322( $columns )
559{
560 $columns['Aprovação'] = 'Aprovação';
561 return $columns;
562}
563
564
565function column_display_wpse_101322( $empty, $column_name, $user_id )
566{
567 if($column_name == "Aprovação"){
568 return '<a href="admin.php?action=promoverole&user_id=' . $user_id . '">Aprovar Membro</a>';
569 }
570
571}
572
573//add_action( 'user_alter_perm', 'promove_user_role_for_adm', 10,0);
574//do_action('user_alter_perm');
575
576function promove_user_role_for_adm(){
577 if(isset($_GET['action'])){
578 if(isset($_GET['user_id']) && $_GET['action'] =='promoverole'){
579 $id = (int)$_GET['user_id'];
580 $user = new WP_User($id);
581 foreach($user->get_role_caps() as $k=>$caps){
582 if($k == "user1analise"){
583 $user->remove_role('user1analise');
584 $user->add_role('usertable1');
585 }elseif($k == "user2analise"){
586 $user->remove_role('user2analise');
587 $user->add_role('usertable2');
588 }elseif($k == "user3analise"){
589 $user->remove_role('user3analise');
590 $user->add_role('usertable3');
591 }elseif($k == "user4analise"){
592 $user->remove_role('user4analise');
593 $user->add_role('usertable4');
594 }elseif($k == "user5analise"){
595 $user->remove_role('user5analise');
596 $user->add_role('usertable5');
597 }elseif($k == "user6analise"){
598 $user->remove_role('user6analise');
599 $user->add_role('usertable6');
600 }elseif($k == "user7analise"){
601 $user->remove_role('user7analise');
602 $user->add_role('usertable7');
603 }elseif($k == "user8analise"){
604 $user->remove_role('user8analise');
605 $user->add_role('usertable8');
606 }
607 }
608
609 //$user->add_role('subscriber');
610 //exit;
611
612 update_user_meta( $id, '_lojista_status' , 2);
613 /*
614 *$mailer = WC()->mailer();
615
616 $mailer->send( get_option( 'admin_email' ), $subject, $mailer->wrap_message( $title, $message ) );
617 */
618 wp_redirect('/wp-admin/users.php');
619 }
620 }
621
622}
623
624add_action('create_subscriber_user', 'create_subscriber_user_func', 10,0);
625do_action('create_subscriber_user');
626
627function create_subscriber_user_func(){
628 //var_dump($_POST);
629 //exit;
630
631 if(empty($_POST['register_subscriber'])){
632 return false;
633 }
634
635 if($_POST['username'] !== ""){
636 $username = wp_slash($_POST['username']);
637 }else{
638 echo "O campo nome é obrigatório";
639 exit;
640 }
641
642 if($_POST['pass'] != "" && $_POST['psw-repeat'] != '' && $_POST['psw-repeat'] == $_POST['psw-repeat']){
643 $pass = wp_slash($_POST['pass']);
644 }
645 else{
646 echo "As senhas não conferem.";
647 exit;
648 }
649
650 if($_POST['email'] != ""){
651 $email = wp_slash($_POST['email']);
652 }
653
654 if($_POST['cnpj'] != ""){
655 $cnpj = wp_slash($_POST['cnpj']);
656 }
657
658 if($_POST['telefone'] != ""){
659 $fone = wp_slash($_POST['telefone']);
660 }
661 else{
662 echo "telefone deve ser preenchido";
663 exit;
664 }
665
666 if($_POST['rsocial'] != ""){
667 $rsocial = wp_slash($_POST['rsocial']);
668 }else{
669 echo "campo obrigatório";
670 exit;
671 }
672
673 if($_POST['estado'] != ""){
674 $estado = wp_slash($_POST['estado']);
675 }else{
676 echo "campo obrigatório";
677 exit;
678 }
679
680 if($_POST['tipoUsuario'] != ""){
681 $tipoUsuario = wp_slash($_POST['tipoUsuario']);
682 }else{
683 echo "campo obrigatório";
684 exit;
685 }
686
687
688 // ----------------------------------------------------
689 // This is just a security precaution, to make sure the above "Config Variables"
690 // have been changed from their default values.
691 // Check that user doesn't already exist
692 if( !username_exists($username) && !email_exists($email) ) {
693 // Create user and set role to administrator
694 $user_id = wp_create_user($username,$pass,$email);
695 if (is_int($user_id))
696 {
697 $wp_user_object = new WP_User($user_id);
698 $wp_user_object->set_role('user1analise');
699 update_user_meta( $user_id, "first_name",$username);
700 update_user_meta( $user_id, "user_email",$email);
701 update_user_meta( $user_id, 'billing_cnpj' , $cnpj);
702 update_user_meta( $user_id, 'rsocial' , $rsocial);
703 update_user_meta( $user_id, 'telefone_lojista' , $fone);
704 update_user_meta( $user_id, '_lojista_status' , 1);
705 update_user_meta( $user_id, 'billing_state' , $estado);
706 update_user_meta( $user_id, 'shipping_state' , $estado);
707 update_user_meta( $user_id, 'user_type' , $tipoUsuario);
708 //enviando email
709 //enviando email
710 $to = 'comercial@vasoecor.com.br';
711 //$to = 'timocabralcarvalho@gmail.com';
712 $subject = 'Cadastro de Lojista';
713 $body = '<h2>Dados do Cadastro de Lojista</h2>';
714 $body .= "<b>Nome:</b>: " . $username . " <br>";
715 $body .= "<b>Email:</b> " . $email . " <br>";
716 $body .= "<b>Estado:</b> " . $estado . " <br>";
717 $body .= "<b>Cnpj: </b>" . $cnpj . " <br>";
718 $body .= "<b>Razão Social:</b> " . $rsocial . " <br>";
719 $body .= "<b>Telefone:</b> " . $fone . " <br>";
720
721 $headers = array('Content-Type: text/html; charset=UTF-8');
722 wp_mail( $to, $subject, $body, $headers );
723
724 wp_redirect("/obrigado-lojista-2/");
725 exit;
726 /*
727 if(isset($_POST['register_subscriber'])){
728 var_dump($_POST);exit;
729 }
730 */
731 //echo 'Successfully created new admin user. Now delete this file!';
732 }
733 else {
734 echo 'Error with wp_insert_user. No users were created.';
735 }
736 }
737 else {
738 echo 'Email já cadastrado na nossa base de dados.';
739 exit;
740 }
741}
742
743
744add_action('edit_user_profile', 'mysite_show_extra_profile_fields');
745function mysite_show_extra_profile_fields($user) {
746
747 $custom_meta_fields = [];
748 $custom_meta_fields['rsocial'] = 'Razão Social';
749 $custom_meta_fields['user_type'] = 'Tipo de Usuário';
750
751 $meta_number = 0;
752 $custom_meta_fields = $custom_meta_fields;
753
754 print('<h3>Dados customizados do Usuário</h3>');
755 print('<table class="form-table">');
756
757 foreach ($custom_meta_fields as $meta_field_name => $meta_disp_name) {
758 $meta_number++;
759 print('<tr>');
760 print('<th><label for="' . $meta_field_name . '">' . $meta_disp_name . '</label></th>');
761 print('<td>');
762 print('<input type="text" name="' . $meta_field_name . '" id="' . $meta_field_name . '" value="' . esc_attr( get_the_author_meta($meta_field_name, $user->ID ) ) . '" class="regular-text" /><br />');
763 print('<span class="description"></span>');
764 print('</td>');
765 print('</tr>');
766 }
767
768 print('</table>');
769}
770
771/*
772function cwp_cash_delivery_disable_customer( $available_gateways ) {
773 global $woocommerce;
774
775 if ( isset( $available_gateways['cod'] ) && current_user_can('subscriber') ) {
776 unset( $available_gateways['cod'] );
777 }
778
779 if ( isset( $available_gateways['pagseguro'] ) && current_user_can('subscriber') ) {
780 unset( $available_gateways['pagseguro'] );
781 }
782
783 return $available_gateways;
784}
785
786add_filter( 'woocommerce_available_payment_gateways', 'cwp_cash_delivery_disable_customer' );
787*/
788//permite acesso via URL para rest request
789
790
791add_filter( 'woocommerce_rest_check_permissions', 'my_woocommerce_rest_check_permissions', 90, 4 );
792function my_woocommerce_rest_check_permissions( $permission, $context, $object_id, $post_type ){
793 return true;
794}
795
796/*
797function widget_categories_args_filter($cat_args) {
798 $exclude_arr = array(117,16,168,1,19);
799
800 if( isset( $cat_args['exclude'] ) && !empty( $cat_args['exclude'] ) )
801 $exclude_arr = array_unique( array_merge( explode( ',', $cat_args['exclude'] ), $exclude_arr ) );
802 $cat_args['exclude'] = implode( ',', $exclude_arr );
803 return $cat_args;
804 }
805
806add_filter( 'widget_categories_args', 'widget_categories_args_filter', 10, 1 );
807*/
808//add_action('init', "updateProducts");
809/*
810function updateProducts(){
811
812//wp_set_object_terms($productID, array('product_tag1','product_tag2','product_tag3'), 'product_tag');
813 if(isset($_GET['script'])){
814
815 // Get draft products.
816 $args = array(
817 'limit' => 300,
818 'return'=>'ids'
819 );
820
821 $products = wc_get_products($args);
822
823 foreach($products as $pId){
824 wp_set_object_terms($pId, array('lojista'), 'product_tag');
825 }
826
827 $args = array(
828 'tags'=>'lojista',
829 'limit'=>200
830 );
831
832 $products2 = wc_get_products( $args );
833
834 var_dump(count($products2));
835 exit;
836
837 }
838
839}
840*/
841/*
842add_action( 'save_post', 'add_tag_to_product', 10, 3 );
843function add_tag_to_product( $post_id, $post, $update ) {
844
845 if ($post->post_type != 'product') return; // Only products
846 if (defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
847 return $post_id;
848
849 // Check the user's permissions.
850 if ( ! current_user_can( 'edit_product', $post_id ) )
851 return $post_id;
852
853 $product = wc_get_product( $post_id ); // The WC_Product object
854 //wp_set_object_terms($product->get_id(), array('lojista'), 'product_tag',$append=true);
855 // if product is not on sale
856 $feature_product = get_post_meta($product->get_id(), '_alg_wc_price_by_user_role_sale_price_subscriber', true );
857 print_r($feature_product);
858 exit;
859
860}
861*/
862/*
863add_filter( 'rest_pre_echo_response', function( $response, $object, $request ) {
864 $product_attribute = array();
865 //$response->data["line_items"] = array("testKey"=>'testValue');
866 for($i=0;$i<count($response['line_items']);$i++){
867 $product[$i] = wc_get_product($response['line_items'][$i]['product_id']);
868 foreach($product[$i]->get_attributes() as $k=>$attribute){
869 if($attribute->get_name() == 'id'){
870 $prod = $attribute;
871 $response['line_items'][$i]['meta_data'] = array("_id_exportacao"=>$prod->get_options()[0]);
872 }
873 }
874
875 }
876 //$response->data['meta_data']['key'] = 'user_rest_request';
877 return $response;
878 }, 10, 3 );
879 */
880
881//add_filter( 'wc_product_has_unique_sku', '__return_false' );
882
883
884//add_action( 'init', 'wpname_unregister_taxonomy' );
885 /*
886function wpname_unregister_taxonomy() {
887 $args = array(
888 'limit' => 200,
889 'return'=>'ids',
890 'tag'=>'instashop'
891 );
892
893 $products = wc_get_products($args);
894 $arraySTR = 'array(';
895 foreach($products as $k=>$prod){
896
897 $arraySTR .= $prod . ',';
898 }
899 $arraySTR .= ');';
900
901 echo($arraySTR);
902 exit;
903}
904*/
905//add_action('init','updateTaxonomy');
906#10% array(13771,10932,9452);
907#50% (array(13842,13771,11591,11585,11579,11576,11575,11569,11566,10982,10980,10978,10976,10973,10960,10958,10956,10932,9372,9369,9367,9364,9363,9327,9321,9196,9192,9187,9179,8900,8867,8838,8810,8782,8754,5445,4611,4586,4408,4382,3851,3579,3466); )
908#alexhanazaki array(9515,9502,9477);
909#andrelenza array(13842,9196,8900,8867,3364,);
910#bacia array(9292,9282);
911#banquetajardim array(9192,4586,);
912#blackfriday array(16092,16085,13771,13266,12556,12548,12544,12534,11591,11585,11579,11576,11575,11569,11566,10982,10980,10978,10976,10973,10960,10958,10956,10932,9571,9562,9556,9548,9536,9515,9502,9477,9452,9372,9369,9367,9364,9363,9327,9321,9292,9282,9252,9244,9228,9220,9192,9187,9177,9170,9164,9150,9144,9138,9103,9078,9069,9061,9054,9017,8981,8959,8937,8900,8867,8838,8810,8782,8754,7693,6244,6213,5800,5766,5724,5619,5586,5541,5507,5482,5445,5326,4611,4586,4487,4408,4382,4334,4324,4317,4281,4264,4205,4146,4087,3970,3912,3851,3652,3618,3579,3562,3466,3436,3364,3289,3237,3080,2793,);
913#casavasap array(9641,9252,9179,9078,8867,4611,4586);
914#combinadinho array(11591,11585,11579,11576,11575,11569,11566,10982,10980,10978,10976,10973,10960,10958,10956,9372,9369,9367,9364,9363,9327,);
915#composicao array(18126,16937,16238,14145,13358,13270,13235,12633,12404,11229,10343,10172,10137,10135,10064,9712,9464,9323,9322,9320,9307,9305,9303,);
916#cumbuca 194 array(3652,2793,);
917#desc array(15713,13266,12556,12548,12544,12534,9292,9252,9244,9179,9061,6213,5724,5445,5303,4611,4586,4334,4205,4087,3579,3562,3436,);
918#desconto array(13771,10932);
919#descontoabril array(15713,9369,5303,3562,);
920#destaque array(16999,16386,15464,15378,15020,15005,15003,15000,14621,12926,12887,12402,12394,12383,12380,10260,10062,);
921#hanazaki array(9515,9502,9477,);
922#home array(4611,4586);
923#jardineira array(8810,3618,3579,);
924#kony array(9069,3080,);
925#macrame array(9177,7693,);
926#minikit array(19184,16450,15813,15807,15804,15797,15232,15226,15220,15213,15211,15208,15202,14998,);
927#oval array(9515,9502,9477,);
928#prato array(4487,4408,);
929#prisma array(8838,8810,8782,);
930#quadrado 199 array(8867,8838,8782,3364,); (pro)
931#ripado array(8900,8867,3364,);
932#rosenbaum array(3652,3618,3579,2793,);
933#suculentas
934#suporte 186 array(16092,16085,9571,9562,9556,9548,9536,9452,9177,8754,7693,4382,4334,4324,4317,4281,4264,);
935#tripe array(4324,4317,4281,4264,);
936#vaso array(9641,9633,9252,9244,9236,9228,9220,9069,8900,8867,8838,8810,8782,3652,3618,3579,3562,3364,3080,2793,);
937#vasoconeliso array(9103,6244,6213,3912,);
938#vietnamita array(9641,9633,9252,9244,9236,9228,9220,);
939#zanini array(9069,3562,3080);
940#30 array(13266,12556,12548,12544,12534,9641,9633,9571,9562,9292,9282,9252,9244,9236,9220,9177,9170,9164,9157,9150,9144,9138,9103,9078,9061,9054,9017,8981,8959,8937,6244,5800,5766,5724,5619,5586,5541,5507,5482,4205,3912,3289,3237,);
941#40 array(16092,16085,15713,9556,9548,9536,9515,9502,9477,9069,5326,5303,3562,);
942#instashop array(18126,16937,16238,14145,13771,13358,13270,13235,12633,12404,11229,10932,10343,10172,10137,10135,10066,10064,9712,9464,9323,9322,9320,9307,9305,9303,);
943/*
944function updateTaxonomy(){
945 if(isset($_GET['exportTax'])){
946 $p = array(18126,16937,16238,14145,13771,13358,13270,13235,12633,12404,11229,10932,10343,10172,10137,10135,10066,10064,9712,9464,9323,9322,9320,9307,9305,9303);
947 foreach($p as $prod):
948 wp_set_object_terms($prod,227, 'product_tag', $append=true);
949 endforeach;
950 echo 'sucesso'; exit;
951 }
952
953}
954*/
955//add_filter('woocommerce_get_price','custom_price_WPA111772', 10, 2);
956//add_filter('woocommerce_get_regular_price','custom_price_WPA111772', 10, 2);
957//add_filter('woocommerce_get_sale_price','custom_price_WPA111772', 10, 2);
958//add_filter( 'woocommerce_product_get_price', 'custom_price_WPA111772', 10, 2 );
959//add_filter( 'woocommerce_product_variation_get_price', 'custom_price_WPA111772', 10, 2);
960//woocommerce_product_variation_get_price (work)
961//woocommerce_variation_prices_regular_price (work)
962
963/**
964 * custom_price_WPA111772
965 *
966 * filter the price based on category and user role
967 * @param $price
968 * @param $product
969 * @return
970 */
971/*
972function custom_price_WPA111772($price, $product) {
973 $priceList = [];
974
975 if (!is_user_logged_in()) return $price;
976 //check if the product is in a category you want, let say shirts
977 //check if the user has a role of dealer using a helper function, see bellow
978 if (has_role_WPA111772('subscriber')){
979 //give user 10% of
980 //print_r($product->get_available_variations());
981 //foreach($product->get_variation_prices()['price'] as $k=>$pricev){
982 // $priceList[] = $pricev;
983 //}
984
985 $price = $price*0.8;
986
987
988 }
989
990 //var_dump($priceList);exit;
991
992 return $price;
993}
994*/
995/**
996* has_role_WPA111772
997*
998* function to check if a user has a specific role
999*
1000* @param string $role role to check against
1001* @param int $user_id user id
1002* @return boolean
1003*/
1004function has_role_WPA111772($role = '',$user_id = null){
1005 if ( is_numeric( $user_id ) )
1006 $user = get_user_by( 'id',$user_id );
1007 else
1008 $user = wp_get_current_user();
1009
1010 if ( empty( $user ) )
1011 return false;
1012
1013 return in_array( $role, (array) $user->roles );
1014}
1015
1016// Applying conditionally a discount for a specific user role
1017//add_action( 'woocommerce_cart_calculate_fees', 'discount_based_on_user_role', 20, 1 );
1018/*
1019function discount_based_on_user_role( $cart ) {
1020 if ( is_admin() && ! defined( 'DOING_AJAX' ) )
1021 return; // Exit
1022
1023 // Only for 'company' user role
1024 #if ( ! current_user_can('company') )
1025 # return; // Exit
1026
1027 // HERE define the percentage discount
1028
1029 ##$discount = $cart->get_subtotal() * $percentage / 100; // Calculation
1030 ##foreach($cart->cart_contents as $k=>$cart){
1031 # $cart['line_subtotal'] = $cart['line_subtotal'] *2;
1032 #}
1033 if (has_role_WPA111772('subscriber')){
1034 //give user 10% of
1035 //print_r($product->get_available_variations());
1036 //foreach($product->get_variation_prices()['price'] as $k=>$pricev){
1037 // $priceList[] = $pricev;
1038 //}
1039
1040 //$price = $price*0.8;
1041 //var_dump($price);
1042
1043 $acrescimo = $cart->get_subtotal() * 0.15;
1044 $cart->add_fee("Acréscimo de 15% para Lojista",$acrescimo,false,$taxClass=false);
1045
1046 }
1047
1048 // print_r($cart['line_subtotal']);
1049 // Applying discount
1050
1051 return $cart;
1052}
1053*/
1054add_filter( 'woocommerce_shortcode_products_query', 'woocommerce_shortcode_products_orderby' );
1055function woocommerce_shortcode_products_orderby( $args ) {
1056 if( is_account_page() && is_user_logged_in() && has_role_WPA111772('subscriber') ){
1057 //$standard_array = array('menu_order','title','date','rand','id');
1058 //$args['meta_key'] = '_alg_wc_price_by_user_role_sale_price_subscriber';
1059 $args['meta_key'] = '_alg_wc_price_by_user_role_per_product_settings_enabled';
1060 $args['meta_value'] = "yes";
1061 //print_r($args);
1062 return $args;
1063 }
1064}
1065
1066add_action('pre_user_query', 'change_user_order');
1067function change_user_order($query) {
1068
1069 $query->query_orderby = ' ORDER BY ID DESC';
1070}
1071
1072add_action( 'woocommerce_check_cart_items', 'spyr_set_min_total' );
1073
1074function spyr_set_min_total() {
1075
1076 if(has_role_WPA111772('subscriber')) {
1077 if(is_cart() || is_checkout()){
1078 global $woocommerce;
1079
1080 $minimum_cart_total = 1000;
1081
1082 $total = WC()->cart->subtotal;
1083
1084 if( $total <= $minimum_cart_total ) {
1085 $saldo = $minimum_cart_total - $total;
1086 $saldo_dec = number_format((float)$saldo, 2, ',', '');
1087 $singular = '<br />Falta <strong>R$ %s</strong> para atingir o valor mínimo.</div>';
1088 $plural = '<br />Faltam <strong>R$ %s</strong> para atingir o valor mínimo.</div>';
1089 if ( $saldo > 1 || $saldo < 1 ) {
1090 $msg = $plural;
1091 } else {
1092 $msg = $singular;
1093 }
1094
1095 if ( $total != 0 ) {
1096 wc_add_notice( sprintf( '<div style="font-size: 15px;"><strong>O Pedido deve ter o valor mínimo de R$ %s.</strong>'
1097 .'<br />O Valor total do seu pedido agora é de <strong>R$ %s</strong>.'
1098 .$msg,
1099 number_format((float)$minimum_cart_total, 2, ',', ''),
1100 number_format((float)$total, 2, ',', ''),
1101 $saldo_dec ),
1102 'error' );
1103 }
1104 }
1105 }
1106 }
1107}
1108
1109add_filter( 'woocommerce_ajax_variation_threshold', 'ww_ajax_variation_threshold', 10, 2 );
1110function ww_ajax_variation_threshold( $default, $product ) {
1111 return 150;
1112}
1113
1114define( 'WC_MAX_LINKED_VARIATIONS', 150 );
1115
1116
1117/*
1118
1119function wc_varb_price_range( $wcv_price, $product ) {
1120
1121 $prefix = sprintf('%s ', __(' ', 'wcvp_range'));
1122
1123 $wcv_reg_min_price = $product->get_variation_regular_price( 'min', true );
1124 $wcv_min_sale_price = $product->get_variation_sale_price( 'min', true );
1125 $wcv_max_price = $product->get_variation_price( 'max', true );
1126 $wcv_min_price = $product->get_variation_price( 'min', true );
1127
1128 $wcv_price = ( $wcv_min_sale_price == $wcv_reg_min_price ) ?
1129 wc_price( $wcv_reg_min_price ) :
1130 '<del>' . wc_price( $wcv_reg_min_price ) . '</del>' . '<ins>' . wc_price( $wcv_min_sale_price ) . '</ins>';
1131
1132 return ( $wcv_min_price == $wcv_max_price ) ?
1133 $wcv_price :
1134 sprintf('%s%s', $prefix, $wcv_price);
1135}
1136
1137add_filter( 'woocommerce_variable_sale_price_html', 'wc_varb_price_range', 10, 2 );
1138add_filter( 'woocommerce_variable_price_html', 'wc_varb_price_range', 10, 2 );*/
1139
1140
1141
1142
1143
1144//add_action( 'woocommerce_before_single_product', 'check_if_variable_first' );
1145/*function check_if_variable_first(){
1146 if ( is_product() ) {
1147 global $post;
1148 $product = wc_get_product( $post->ID );
1149 if ( $product->is_type( 'variable' ) ) {
1150 // removing the price of variable products
1151remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );
1152
1153// Change location of
1154add_action( 'woocommerce_single_product_summary', 'custom_wc_template_single_price', 10 );
1155function custom_wc_template_single_price(){
1156 global $product;
1157
1158// Variable product only
1159if($product->is_type('variable')):
1160
1161 // Main Price
1162 $prices = array( $product->get_variation_price( 'min', true ), $product->get_variation_price( 'max', true ) );
1163 $price = $prices[0] !== $prices[1] ? sprintf( __( '%1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );
1164
1165 // Sale Price
1166 $prices = array( $product->get_variation_regular_price( 'min', true ), $product->get_variation_regular_price( 'max', true ) );
1167 sort( $prices );
1168 $saleprice = $prices[0] !== $prices[1] ? sprintf( __( '%1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );
1169
1170 if ( $price !== $saleprice && $product->is_on_sale() ) {
1171 $price = '<del>' . $saleprice . $product->get_price_suffix() . '</del> <ins>' . $price . $product->get_price_suffix() . '</ins>';
1172 }
1173
1174 ?>
1175 <style>
1176 div.woocommerce-variation-price,
1177 div.woocommerce-variation-availability,
1178 div.hidden-variable-price {
1179 height: 0px !important;
1180 overflow:hidden;
1181 position:relative;
1182 line-height: 0px !important;
1183 font-size: 0% !important;
1184 }
1185 </style>
1186 <script>
1187 jQuery(document).ready(function($) {
1188 $('select').click( function(){
1189 if( '' != $('input.variation_id').val() ){
1190 //$('p.price').html($('div.woocommerce-variation-price > span.price').html()).append('<p class="availability">'+$('div.woocommerce-variation-availability').html()+'</p>');
1191 //alert($('input.variation_id').val());
1192 } else {
1193 $('p.price').html($('div.hidden-variable-price').html());
1194 if($('p.availability'))
1195 $('p.availability').remove();
1196 console.log('NULL');
1197 }
1198 });
1199 });
1200 </script>
1201 <?php
1202
1203 echo '<p class="price">'.$price.'</p>
1204 <div class="hidden-variable-price" >'.$price.'</div>';
1205
1206endif;
1207}
1208
1209 }
1210 }
1211}*/
1212add_action('woocommerce_before_single_product', 'check_if_variable_first', 1);
1213function check_if_variable_first()
1214{
1215 if (is_product())
1216 {
1217 global $post;
1218 $product = wc_get_product($post->ID);
1219 //se existir o attr cor, não aplica as regras de ocutação de preços variáveis
1220 $countAttr = count($product->get_attributes());
1221 $pa_cor = $product->get_attribute('pa_cor');
1222
1223
1224 if($pa_cor != "" && $countAttr === 1){
1225 return false;
1226 }
1227
1228 if ($product->is_type('variable'))
1229 {
1230 // removing the price of variable products
1231 remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_price', 10);
1232
1233 // Change location of
1234 add_action('woocommerce_single_product_summary', 'custom_wc_template_single_price', 10);
1235 function custom_wc_template_single_price()
1236 {
1237 global $product;
1238
1239 //Variable product only
1240 if ($product->is_type('variable')):
1241 /*
1242 // Main Price
1243 $variationPriceMin = $product->get_variation_price('min', true);
1244 $variationPriceMax = $product->get_variation_price('max', true);
1245 $copyVariationMin = $variationPriceMin;
1246 $copyVariationMax = $variationPriceMax;
1247
1248 $n = new Decimal;
1249 $n->increase($copyVariationMin);
1250 $percentual = 10.0 / 100.0;
1251 $valor_final = $n->multiply($percentual);
1252 $variationDiscountPrice = (string) $valor_final;
1253
1254 $m = new Decimal;
1255 $m->increase($copyVariationMin);
1256 $percentualM = 10.0 / 100.0;
1257 $valor_finalM = $m->multiply($percentualM);
1258 $variationDiscountPriceM = (string) $valor_finalM;
1259
1260 //$n->increase
1261 //var_dump((string)$n->subtract($variationDiscountPrice));
1262
1263 $prices = array((string)$n->subtract($variationDiscountPrice,$variationPriceMin),
1264 (string)$m->subtract($variationDiscountPriceM,$variationPriceMax)
1265 );
1266
1267 $price = $prices[0] !== $prices[1] ? sprintf(__('%1$s', 'woocommerce') , wc_price($prices[0])) : wc_price($prices[0]);
1268 //var_dump($price);
1269 // Sale Price
1270 $prices = array(
1271 $product->get_variation_regular_price('min', true) ,
1272 $product->get_variation_regular_price('max', true)
1273 );
1274
1275 sort($prices);
1276 $saleprice = $prices[0] !== $prices[1] ? sprintf(__('%1$s', 'woocommerce') , wc_price($prices[0])) : wc_price($prices[0]);
1277
1278 if ($price !== $saleprice && $product->is_on_sale())
1279 {
1280 $price = '<del>' . $saleprice . $product->get_price_suffix() . '</del> <ins>' . $price . $product->get_price_suffix() . '</ins>';
1281 }
1282 */
1283 // Main Price
1284 $prices = array( $product->get_variation_price( 'min', true ), $product->get_variation_price( 'max', true ) );
1285 $price = $prices[0] !== $prices[1] ? sprintf( __( '<span class="from-price"></span> %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );
1286
1287 // Sale Price
1288 $prices = array( $product->get_variation_regular_price( 'min', true ), $product->get_variation_regular_price( 'max', true ) );
1289 sort( $prices );
1290 $saleprice = $prices[0] !== $prices[1] ? sprintf( __( '<span class="from-price"></span> %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );
1291
1292 if ( $price !== $saleprice && $product->is_on_sale() ) {
1293 $price = '<del>' . $saleprice . $product->get_price_suffix() . '</del> <ins>' . $price . $product->get_price_suffix() . '</ins>';
1294 }
1295
1296?>
1297 <style>
1298 div.woocommerce-variation-price,
1299 div.woocommerce-variation-availability,
1300 div.hidden-variable-price {
1301 height: 0px !important;
1302 overflow:hidden;
1303 position:relative;
1304 line-height: 0px !important;
1305 font-size: 0% !important;
1306 }
1307 </style>
1308 <script>
1309 jQuery(document).ready(function() {
1310 jQuery('select').change( function(e){
1311 //alert(jQuery('input.variation_id').val());
1312 //e.preventDefault();
1313 if( '' != jQuery('input.variation_id').val() && 0 != jQuery('input.variation_id').val()){
1314 //alert(jQuery('div.woocommerce-variation-price > span.price').html());
1315 //jQuery('p.price').html(jQuery('div.woocommerce-variation-price > span.price').html()).append('<p class="availability">'+jQuery('div.woocommerce-variation-availability').html()+'</p>');
1316 jQuery('p.price').hide();
1317 //alert(jQuery('p.price').val());
1318 //alert(jQuery('input.variation_id').val());
1319 } else {
1320 //alert(jQuery('input.variation_id').val());
1321 jQuery('p.price').html(jQuery('div.hidden-variable-price').html());
1322 if(jQuery('p.availability'))
1323 jQuery('p.availability').remove();
1324 //console.log('NULL');
1325 //alert(jQuery('.woocommerce-variation-price').length);
1326 //var countClick = 0;
1327
1328 var countOpenVariablePrice = 0;
1329 var isVariableProductEqualPrice = 0;
1330 var isVariableProductEqualPriceDiff = 0;
1331
1332 jQuery(".swatch-enabled").click(function(){
1333
1334 //alert(jQuery('div.woocommerce-variation-availability').text());
1335 //alert(jQuery('p.availability').text());
1336 jQuery( '.variations_form' ).each( function() {
1337 jQuery(this).on( 'found_variation', function( event, variation ) {
1338 //alert(variation);//all details here
1339 var price = variation.display_price;//selectedprice
1340 var priceNormal = jQuery('.woocommerce-variation-price .amount').text();
1341 //alert(priceNormal);
1342 //não existe um preço de variação carregado no dom
1343 if(priceNormal === ""){
1344 isVariableProductEqualPrice++;
1345 }else{
1346 //variações já carregadas no DOM
1347 isVariableProductEqualPriceDiff++;
1348 //alert(isVariableProductEqualPriceDiff);
1349 }
1350
1351 //alert(isVariableProductEqualPrice);
1352 //alert(isVariableProductEqualPriceDiff);
1353 //alert(priceNormal === "");
1354 //alert(isVariableProductEqualPriceDiff);
1355 if(jQuery('.woocommerce-variation.single_variation' + '[style="display: none;"]').length >= 1
1356 && jQuery('.woocommerce-variation-price').text() === ""){
1357 //alert(jQuery('p.price').text());
1358 //alert(jQuery('div.hidden-variable-price').text());
1359 //alert(jQuery('span.woocommerce-Price-currencySymbol').text());
1360 //alert(countOpenVariablePrice);
1361
1362 /*if(countOpenVariablePrice == 0 && isVariableProductEqualPrice == 1){
1363 //jQuery('p.price').remove();
1364 countOpenVariablePrice++;
1365 }*/
1366
1367 //alert(isVariableProductEqualPriceDiff);
1368
1369 if(isVariableProductEqualPriceDiff > 0 && countOpenVariablePrice == 0){
1370
1371 jQuery('p.price').remove();
1372 countOpenVariablePrice++;
1373 }
1374 //alert(countClick);
1375 //countClick++;
1376 }else{
1377 //jQuery('p.price').show();
1378 /*if(isVariableProductEqualPrice === 1){
1379 //jQuery('p.price').remove();
1380 }*/
1381
1382 //alert(isVariableProductEqualPriceDiff);
1383 if(isVariableProductEqualPriceDiff > 0){
1384 jQuery('p.price').remove();
1385 }
1386
1387 }
1388
1389 });
1390 });
1391 //alert('aq');
1392 /*if(jQuery('.woocommerce-variation-price').text() === jQuery('p.price').text()){
1393 isVariableProductEqualPrice++;
1394 }*/
1395 //alert(jQuery('p.availability').text());
1396 //variações não estão carregadas no DOM
1397
1398 });
1399 }
1400 });
1401 });
1402 </script>
1403 <?php
1404 echo '<p class="price">' . $price . '</p>
1405 <div class="hidden-variable-price" >' . $price . '</div>';
1406
1407 endif;
1408 }
1409
1410 }
1411 }
1412}
1413
1414
1415remove_action ('woocommerce_single_variation', 'woocommerce_single_variation', 10);
1416add_action ('woocommerce_before_variations_form', 'woocommerce_single_variation', 20);
1417
1418
1419remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_excerpt', 20);
1420add_action('woocommerce_after_add_to_cart_form', 'woocommerce_template_single_excerpt');
1421
1422/*
1423add_action( 'woocommerce_single_product_summary', 'unavailable_product_display_message', 30 );
1424function unavailable_product_display_message() {
1425 global $product;
1426
1427 if($product->is_purchasable() ){
1428 echo '<input type="buttom">' . __("This product is currently unavailable.") . '</p>';
1429 }
1430}*/