· 4 years ago · Mar 01, 2021, 07:12 PM
1<?php
2include "json.php";
3ini_set('memory_limit', '1500M');
4
5if ( ! defined( 'ABSPATH' ) ) {
6 exit; // Exit if accessed directly
7}
8
9if ( ! isset( $content_width ) ) {
10 $content_width = 900;
11}
12if ( ! class_exists( 'Antive_Functions' ) ) {
13 class Antive_Functions {
14 /**
15 * Instance of the class.
16 *
17 * @since 1.0.0
18 *
19 * @var object
20 */
21 protected static $instance = null;
22
23 /**
24 * Initialize the plugin by setting localization and loading public scripts
25 * and styles.
26 *
27 * @since 1.0.0
28 */
29 public function __construct() {
30 add_action( 'after_setup_theme', array( $this, 'settup' ) );
31 add_action( 'widgets_init', array( $this, 'widgets_init' ) );
32 add_action( 'init', array( $this, 'init_theme_method' ) );
33 add_action( 'wp_enqueue_scripts', array( $this, 'scripts' ) );
34 add_action( 'upload_mimes', array( $this, 'antive_add_svg_type_upload' ), 1 );
35 add_action( 'admin_enqueue_scripts', array( $this, 'admin_script' ) );
36 add_filter( 'get_default_comment_status', array( $this, 'open_default_comments_for_page' ), 10, 3 );
37 add_action( 'wp_ajax_antive_remove_cart_item_via_ajax', array(
38 $this,
39 'antive_remove_cart_item_via_ajax'
40 ) );
41 add_action( 'wp_ajax_nopriv_antive_remove_cart_item_via_ajax', array(
42 $this,
43 'antive_remove_cart_item_via_ajax'
44 ) );
45 add_action( 'wp_ajax_antive_instant_search_data', array( $this, 'antive_instant_search_data' ) );
46 add_action( 'wp_ajax_nopriv_antive_instant_search_data', array( $this, 'antive_instant_search_data' ) );
47 if ( ! is_admin() ) {
48 add_filter( 'script_loader_src', array( $this, 'antive_remove_query_string_version' ) );
49 add_filter( 'style_loader_src', array( $this, 'antive_remove_query_string_version' ) );
50 }
51 $this->includes();
52 }
53
54 function init_theme_method() {
55 add_thickbox();
56 }
57
58 public function settup() {
59 /*
60 * Make theme available for translation.
61 * Translations can be filed in the /languages/ directory.
62 * If you're building a theme based on boutique, use a find and replace
63 * to change 'antive' to the name of your theme in all the template files
64 */
65 load_theme_textdomain( 'antive', get_template_directory() . '/languages' );
66 // Add default posts and comments RSS feed links to head.
67 add_theme_support( 'automatic-feed-links' );
68 /*
69 * Let WordPress manage the document title.
70 * By adding theme support, we declare that this theme does not use a
71 * hard-coded <title> tag in the document head, and expect WordPress to
72 * provide it for us.
73 */
74 add_theme_support( 'title-tag' );
75 /*
76 * Enable support for Post Thumbnails on posts and pages.
77 *
78 * See: https://codex.wordpress.org/Function_Reference/add_theme_support#Post_Thumbnails
79 */
80 add_theme_support( 'post-thumbnails' );
81 //set_post_thumbnail_size(825, 510, true);
82 add_image_size( 'shop_cart_thumbnail', 220, 180, true );
83 /*This theme uses wp_nav_menu() in two locations.*/
84 register_nav_menus( array(
85 'primary' => esc_html__( 'Primary Menu', 'antive' ),
86 'double-menu' => esc_html__( 'Double Menu', 'antive' ),
87 ) );
88 /*
89 * Switch default core markup for search form, comment form, and comments
90 * to output valid HTML5.
91 */
92 add_theme_support( 'html5', array(
93 'search-form',
94 'comment-form',
95 'comment-list',
96 'gallery',
97 'caption'
98 ) );
99 add_theme_support( 'post-formats', array( 'video', 'audio', 'gallery', 'link', 'quote', 'image' ) );
100 /*Support woocommerce*/
101 add_theme_support( 'woocommerce' );
102 add_theme_support( 'wc-product-gallery-lightbox' );
103 add_theme_support( 'wc-product-gallery-slider' );
104 add_theme_support( 'wc-product-gallery-zoom' );
105
106 self::support_gutenberg();
107 }
108
109 public function support_gutenberg() {
110 // Add support for Block Styles.
111 add_theme_support( 'wp-block-styles' );
112
113 // Add support for full and wide align images.
114 add_theme_support( 'align-wide' );
115
116 // Add support for editor styles.
117 add_theme_support( 'editor-styles' );
118
119 // Enqueue editor styles.
120 add_editor_style( 'style-editor.css' );
121
122 // Add custom editor font sizes.
123 add_theme_support(
124 'editor-font-sizes',
125 array(
126 array(
127 'name' => __( 'Small', 'funiter' ),
128 'shortName' => __( 'S', 'funiter' ),
129 'size' => 13,
130 'slug' => 'small',
131 ),
132 array(
133 'name' => __( 'Normal', 'funiter' ),
134 'shortName' => __( 'M', 'funiter' ),
135 'size' => 14,
136 'slug' => 'normal',
137 ),
138 array(
139 'name' => __( 'Large', 'funiter' ),
140 'shortName' => __( 'L', 'funiter' ),
141 'size' => 36,
142 'slug' => 'large',
143 ),
144 array(
145 'name' => __( 'Huge', 'funiter' ),
146 'shortName' => __( 'XL', 'funiter' ),
147 'size' => 48,
148 'slug' => 'huge',
149 ),
150 )
151 );
152
153 // Add support for responsive embedded content.
154 add_theme_support( 'responsive-embeds' );
155 }
156
157 function antive_remove_query_string_version( $src ) {
158 $arr_params = array( 'ver', 'id', 'type', 'version' );
159 $src = urldecode( remove_query_arg( $arr_params, $src ) );
160
161 return $src;
162 }
163
164 /**
165 * Register widget area.
166 *
167 * @since Antive 1.0
168 *
169 * @link https://codex.wordpress.org/Function_Reference/register_sidebar
170 */
171 function widgets_init() {
172 register_sidebar( array(
173 'name' => esc_html__( 'Main Sidebar', 'antive' ),
174 'id' => 'main-sidebar',
175 'before_widget' => '<div id="%1$s" class="widget %2$s">',
176 'after_widget' => '</div>',
177 'before_title' => '<h2 class="widgettitle">',
178 'after_title' => '<span class="arow"></span></h2>',
179 ) );
180 register_sidebar( array(
181 'name' => esc_html__( 'Shop Widget Area', 'antive' ),
182 'id' => 'shop-widget-area',
183 'description' => esc_html__( 'Add widgets here to appear in your sidebar.', 'antive' ),
184 'before_widget' => '<div id="%1$s" class="widget %2$s">',
185 'after_widget' => '</div>',
186 'before_title' => '<h2 class="widgettitle">',
187 'after_title' => '<span class="arow"></span></h2>',
188 ) );
189 register_sidebar( array(
190 'name' => esc_html__( 'Single Shop Widget Area', 'antive' ),
191 'id' => 'single-shop-widget-area',
192 'description' => esc_html__( 'Add widgets here to appear in your sidebar.', 'antive' ),
193 'before_widget' => '<div id="%1$s" class="widget %2$s">',
194 'after_widget' => '</div>',
195 'before_title' => '<h2 class="widgettitle">',
196 'after_title' => '<span class="arow"></span></h2>',
197 ) );
198 }
199
200 /**
201 * Register Google fonts for Twenty Fifteen.
202 *
203 * @since Lucky Shop 1.0
204 *
205 * @return string Google fonts URL for the theme.
206 */
207 function google_fonts_url() {
208 $fonts_url = '';
209 $fonts = array();
210 $subsets = 'latin,latin-ext';
211
212 /*
213 * Translators: If there are characters in your language that are not supported
214 * by Poppins, translate this to 'off'. Do not translate into your own language.
215 */
216 if ( 'off' !== _x( 'on', 'Poppins font: on or off', 'antive' ) ) {
217 $fonts[] = 'Poppins:300,400,500,600,700';
218 }
219
220 /*
221 * Translators: If there are characters in your language that are not supported
222 * by Playfair Display, translate this to 'off'. Do not translate into your own language.
223 */
224 if ( 'off' !== _x( 'on', 'Playfair Display font: on or off', 'antive' ) ) {
225 $fonts[] = 'Playfair Display:400,400i,700,700i';
226 }
227
228 /*
229 * Translators: To add an additional character subset specific to your language,
230 * translate this to 'greek', 'cyrillic', 'devanagari' or 'vietnamese'. Do not translate into your own language.
231 */
232 $subset = _x( 'no-subset', 'Add new subset (greek, cyrillic, devanagari, vietnamese)', 'antive' );
233
234 if ( 'cyrillic' == $subset ) {
235 $subsets .= ',cyrillic,cyrillic-ext';
236 } elseif ( 'greek' == $subset ) {
237 $subsets .= ',greek,greek-ext';
238 } elseif ( 'devanagari' == $subset ) {
239 $subsets .= ',devanagari';
240 } elseif ( 'vietnamese' == $subset ) {
241 $subsets .= ',vietnamese';
242 }
243
244 if ( $fonts ) {
245 $fonts_url = add_query_arg(
246 array(
247 'family' => urlencode( implode( '|', $fonts ) ),
248 'subset' => urlencode( $subsets ),
249 ), 'https://fonts.googleapis.com/css'
250 );
251 }
252
253 return $fonts_url;
254 }
255
256 /**
257 * Enqueue scripts and styles.
258 *
259 * @since antive 1.0
260 */
261 function scripts() {
262 $enable_map = get_post_meta( get_the_ID(), 'antive_map_settings', true );
263 if ( $enable_map == 'global' ) {
264 $antive_enable_map = antive_option( 'antive_enable_map', true );
265 } elseif ( $enable_map == 'enable' ) {
266 $antive_enable_map = true;
267 } else {
268 $antive_enable_map = false;
269 }
270 $temp_uri = get_template_directory_uri();
271 $enable_smooth = antive_option( 'antive_enable_smoothscroll', false );
272 // Load fonts
273 wp_enqueue_style( 'antive-googlefonts', $this->google_fonts_url(), array(), null );
274 /*Load our main stylesheet.*/
275 wp_enqueue_style( 'antive-libs', trailingslashit( $temp_uri ) . 'css/libs.min.css', array(), '1.0' );
276 wp_enqueue_style( 'owl-carousel', trailingslashit( $temp_uri ) . 'css/owl.carousel.min.css', array(), '1.0' );
277 wp_enqueue_style( 'antive-main-style', get_stylesheet_uri() );
278 if ( is_rtl() ) {
279 wp_enqueue_style( 'bootstrap-rtl', trailingslashit( $temp_uri ) . 'css/bootstrap.rtl.min.css', array(), '1.0' );
280 }
281 if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
282 wp_enqueue_script( 'comment-reply' );
283 }
284 /*Load lib js*/
285 wp_enqueue_script( 'antive-libs', trailingslashit( $temp_uri ) . 'js/libs.min.js', array( 'jquery' ), false, true );
286 if ( $enable_smooth ) {
287 wp_enqueue_script( 'SmoothScroll', trailingslashit( $temp_uri ) . 'js/SmoothScroll.min.js', array( 'jquery' ), false, true );
288 }
289 wp_enqueue_script( 'slick', trailingslashit( $temp_uri ) . 'js/slick.js', array( 'jquery' ), '1.0', true );
290 if ( class_exists( 'WooCommerce' ) ) {
291 if ( is_singular( 'product' ) ) {
292 wp_enqueue_script( 'html5lightbox', trailingslashit( $temp_uri ) . 'js/html5lightbox.min.js', array(), '1.0', true );
293 }
294 }
295
296 if ( $antive_enable_map ) {
297 $map_api_key = antive_option( 'map_api_key', '' );
298 if ( $map_api_key ) {
299 wp_enqueue_script( 'maps', 'https://maps.googleapis.com/maps/api/js?key=' . esc_attr( $map_api_key ) . '', array( 'jquery' ), '1.0', true );
300 } else {
301 wp_enqueue_script( 'maps', 'https://maps.googleapis.com/maps/api/js?sensor=true', array( 'jquery' ), '1.0', true );
302 }
303 }
304 $antive_enable_lazy = antive_option( 'antive_enable_lazy', false );
305 if ( $antive_enable_lazy ) {
306 /* http://jquery.eisbehr.de/lazy */
307 wp_enqueue_script( 'lazyload', get_theme_file_uri( '/js/lazyload.min.js' ), array(), false, true );
308 }
309
310 wp_enqueue_script( 'antive-blog-masonry', trailingslashit( $temp_uri ) . 'js/blog.masonry.js', array( 'jquery' ), '1.0', true );
311 wp_enqueue_script( 'antive-script', trailingslashit( $temp_uri ) . 'js/functions.js', array( 'jquery' ), '1.0', true );
312 $antive_enable_sticky_menu = antive_option( 'antive_enable_sticky_menu', 1 );
313 $show_mini_cart_on_adding_to_cart = antive_option( 'show_mini_cart_on_adding_to_cart', 0 );
314
315 wp_localize_script( 'antive-script', 'antive_ajax_fontend', array(
316 'ajaxurl' => admin_url( 'admin-ajax.php' ),
317 'security' => wp_create_nonce( 'antive_ajax_fontend' ),
318 'antive_enable_sticky_menu' => $antive_enable_sticky_menu,
319 'show_mini_cart_on_adding_to_cart' => $show_mini_cart_on_adding_to_cart,
320 'text' => array(
321 'load_more' => esc_html__( 'Load More', 'antive' ),
322 'no_more_product' => esc_html__( 'No More Product', 'antive' )
323 ),
324 'html' => array(
325 'countdown' => '<div class="countdown-inner">
326 <div class="counter-item">
327 <span class="number">%D</span>
328 <span class="lbl">' . esc_html__( 'Days', 'antive' ) . '</span>
329 </div>
330 <div class="counter-item">
331 <span class="number">%H</span>
332 <span class="lbl">' . esc_html__( 'Hrs', 'antive' ) . '</span>
333 </div>
334 <div class="counter-item">
335 <span class="number">%M</span>
336 <span class="lbl">' . esc_html__( 'Mins', 'antive' ) . '</span>
337 </div>
338 <div class="counter-item">
339 <span class="number">%S</span>
340 <span class="lbl">' . esc_html__( 'Secs', 'antive' ) . '</span>
341 </div>
342 </div>',
343 'countdown_admin_menu' => '<div class="countdown-inner">
344 <div class="counter-item">
345 <span class="number">%D</span>
346 <span class="lbl">' . esc_html__( 'D', 'antive' ) . '</span>
347 </div>
348 <div class="counter-item">
349 <span class="number">%H</span>
350 <span class="lbl">' . esc_html__( 'H', 'antive' ) . '</span>
351 </div>
352 <div class="counter-item">
353 <span class="number">%M</span>
354 <span class="lbl">' . esc_html__( 'M', 'antive' ) . '</span>
355 </div>
356 <div class="counter-item">
357 <span class="number">%S</span>
358 <span class="lbl">' . esc_html__( 'S', 'antive' ) . '</span>
359 </div>
360 </div>'
361 ),
362
363 ) );
364 wp_localize_script( 'antive-script', 'antive_search_ajax_fontend', array(
365 'ajaxurl' => admin_url( 'admin-ajax.php' ),
366 'security' => wp_create_nonce( 'antive_search_ajax_fontend' ),
367 ) );
368 wp_localize_script( 'antive-blog.masonry', 'antive_ajax_fontend', array(
369 'ajaxurl' => admin_url( 'admin-ajax.php' ),
370 'security' => wp_create_nonce( 'antive_ajax_fontend' ),
371 ) );
372 // Custom localize script
373 wp_localize_script( 'antive-script', 'ZIGG_Data_Js', antive_custom_data_js() );
374
375 }
376
377 function admin_script() {
378 $temp_uri = get_template_directory_uri();
379 wp_enqueue_script( 'jquery-ui-sortable' );
380 wp_enqueue_style( 'antive-googlefonts', $this->google_fonts_url(), array(), null );
381 wp_enqueue_style( 'simpleline-icons', trailingslashit( $temp_uri ) . 'css/simple-line-icons.css', array(), '1.0' );
382 wp_enqueue_style( 'admin-redux', trailingslashit( $temp_uri ) . 'framework/assets/css/admin-redux.css', array(), '1.0' );
383
384 wp_enqueue_script( 'admin-js', trailingslashit( $temp_uri ) . 'framework/assets/js/admin.js', array( 'jquery' ), '1.0', true );
385 wp_enqueue_script( 'antive-backend-script', trailingslashit( $temp_uri ) . '/js/backend.js', array(), false, true );
386 }
387
388 /**
389 * Filter whether comments are open for a given post type.
390 *
391 * @param string $status Default status for the given post type,
392 * either 'open' or 'closed'.
393 * @param string $post_type Post type. Default is `post`.
394 * @param string $comment_type Type of comment. Default is `comment`.
395 *
396 * @return string (Maybe) filtered default status for the given post type.
397 */
398 function open_default_comments_for_page( $status, $post_type, $comment_type ) {
399 if ( 'page' == $post_type ) {
400 return 'open';
401 }
402
403 return $status;
404 /*You could be more specific here for different comment types if desired*/
405 }
406
407 public function includes() {
408 include_once( 'framework/framework.php' );
409 }
410
411 // REMOVE CART ITEM
412 function antive_remove_cart_item_via_ajax() {
413
414 $response = array(
415 'message' => '',
416 'fragments' => '',
417 'cart_hash' => '',
418 'mini_cart_html' => '',
419 'err' => 'no'
420 );
421
422 $cart_item_key = isset( $_POST['cart_item_key'] ) ? sanitize_text_field( $_POST['cart_item_key'] ) : '';
423 $nonce = isset( $_POST['nonce'] ) ? trim( $_POST['nonce'] ) : '';
424
425 if ( $cart_item_key == '' || $nonce == '' ) {
426 $response['err'] = 'yes';
427 wp_send_json( $response );
428 }
429
430 if ( ( wp_verify_nonce( $nonce, 'woocommerce-cart' ) ) ) {
431 if ( $cart_item = WC()->cart->get_cart_item( $cart_item_key ) ) {
432 WC()->cart->remove_cart_item( $cart_item_key );
433
434 $product = wc_get_product( $cart_item['product_id'] );
435
436 $item_removed_title = apply_filters( 'woocommerce_cart_item_removed_title', $product ? sprintf( _x( '“%s”', 'Item name in quotes', 'antive' ), $product->get_name() ) : __( 'Item', 'antive' ), $cart_item );
437
438 // Don't show undo link if removed item is out of stock.
439 if ( $product->is_in_stock() && $product->has_enough_stock( $cart_item['quantity'] ) ) {
440 $removed_notice = sprintf( __( '%s removed.', 'antive' ), $item_removed_title );
441 $removed_notice .= ' <a href="' . esc_url( WC()->cart->get_undo_url( $cart_item_key ) ) . '">' . __( 'Undo?', 'antive' ) . '</a>';
442 } else {
443 $removed_notice = sprintf( __( '%s removed.', 'antive' ), $item_removed_title );
444 }
445
446 wc_add_notice( $removed_notice );
447 }
448 } else {
449 $response['message'] = esc_html__( 'Security check error!', 'antive' );
450 $response['err'] = 'yes';
451 wp_send_json( $response );
452 }
453
454 ob_start();
455 woocommerce_mini_cart();
456 $mini_cart = ob_get_clean();
457
458 $response['fragments'] = apply_filters( 'woocommerce_add_to_cart_fragments', array(
459 'div.widget_shopping_cart_content' => '<div class="widget_shopping_cart_content">' . $mini_cart . '</div>',
460 )
461 );
462 $response['cart_hash'] = apply_filters( 'woocommerce_add_to_cart_hash', WC()->cart->get_cart_for_session() ? md5( json_encode( WC()->cart->get_cart_for_session() ) ) : '', WC()->cart->get_cart_for_session() );
463 $response['mini_cart_html'] = $mini_cart;
464
465 wp_send_json( $response );
466 die();
467 }
468
469 /* INSTANT SEARCH */
470 function antive_instant_search_data() {
471 $response = array(
472 'array' => '',
473 'message' => '',
474 'success' => 'no',
475 );
476 $args = array(
477 'post_type' => 'product',
478 'posts_per_page' => - 1
479 );
480 $posts = new WP_Query( $args );
481 if ( $posts->have_posts() ) { ?>
482
483 <?php while ( $posts->have_posts() ) { ?>
484 <?php
485 $posts->the_post();
486 ob_start(); ?>
487 <div <?php post_class( 'product-item-search col-lg-15 col-md-3 col-sm-4 col-xs-6 col-ts-12 ' ); ?>>
488 <div class="post-thumb">
489 <?php
490 $image = antive_resize_image( get_post_thumbnail_id(), null, 250, 250, true, true, false );
491 ?>
492 <a href="<?php the_permalink() ?>">
493 <img width="<?php echo esc_attr( $image['width'] ); ?>"
494 height="<?php echo esc_attr( $image['height'] ); ?>"
495 class="attachment-post-thumbnail wp-post-image"
496 src="<?php echo esc_attr( $image['url'] ) ?>"
497 alt="<?php the_title(); ?>"/>
498 </a>
499 </div>
500 <div class="product-info">
501 <h3 class="post-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
502 </h3>
503 <?php
504 $product = new WC_Product( get_the_ID() );
505 $rating_count = $product->get_rating_count();
506 $average = $product->get_average_rating();
507 printf( '<div class="price">' . esc_html__( 'Price', 'antive' ) . ' : %s </div>', $product->get_price_html() );
508 printf( '<div class="rating"> %s </div>', wc_get_rating_html( $average, $rating_count ) );
509 ?>
510 </div>
511 </div>
512 <?php
513 $post_html = ob_get_clean();
514 $post_data[] = array(
515 'post_title' => esc_html( get_the_title() ),
516 'post_link' => esc_url( get_permalink() ),
517 'thumb' => $image,
518 'post_html' => $post_html
519 );
520 ?>
521 <?php } ?>
522
523 <?php }
524 wp_reset_postdata();
525 $response['array'] = $post_data;
526 $response['success'] = 'yes';
527 wp_send_json( $response );
528 die();
529 }
530
531 public function antive_add_svg_type_upload( $file_types ) {
532 $new_filetypes = array();
533 $new_filetypes['svg'] = 'image/svg+xml';
534 $file_types = array_merge( $file_types, $new_filetypes );
535
536 return $file_types;
537 }
538 }
539
540 new Antive_Functions();
541}
542/* TABS AJAX */
543if ( ! function_exists( 'antive_tab_product_via_ajax' ) ) {
544 function antive_tab_product_via_ajax() {
545 $response = array(
546 'html' => '',
547 'message' => '',
548 'success' => 'no'
549 );
550 $decode = isset( $_POST['decode'] ) ? $_POST['decode'] : '';
551 $the_content = str_replace( '\"', '"', $decode );
552 ob_start();
553 ?>
554
555 <?php echo do_shortcode( $the_content ); ?>
556
557 <?php
558 $response['html'] = ob_get_clean();
559 $response['success'] = 'ok';
560 wp_send_json( $response );
561 die();
562 }
563}
564add_action( 'wp_ajax_antive_tab_product_via_ajax', 'antive_tab_product_via_ajax' );
565add_action( 'wp_ajax_nopriv_antive_tab_product_via_ajax', 'antive_tab_product_via_ajax' );
566
567/*Comming soon*/
568if ( ! function_exists( 'antive_coming_soon_redirect' ) ) {
569 function antive_coming_soon_redirect() {
570 global $antive;
571 $is_coming_soon_mode = antive_option( 'opt_enable_coming_soon_mode', false );
572 $disable_if_date_smaller_than_current = antive_option( 'opt_disable_coming_soon_when_date_small', false );
573 $coming_date = isset( $antive['opt_coming_soon_date'] ) ? $antive['opt_coming_soon_date'] : '';
574 $today = date( 'm/d/Y' );
575 if ( trim( $coming_date ) == '' || strtotime( $coming_date ) <= strtotime( $today ) ) {
576 if ( $disable_if_date_smaller_than_current ) {
577 $is_coming_soon_mode = false;
578 }
579 }
580 // Dont't show coming soon page if is user logged in or is not coming soon mode on
581 if ( is_user_logged_in() || ! $is_coming_soon_mode ) {
582 return;
583 }
584 antive_coming_soon_html(); // Locate in theme_coming_soon_template.php
585 exit();
586 }
587
588 add_action( 'template_redirect', 'antive_coming_soon_redirect' );
589}
590if ( ! function_exists( 'antive_coming_soon_mode_admin_toolbar' ) ) {
591 // Add Toolbar Menus
592 function antive_coming_soon_mode_admin_toolbar() {
593 global $wp_admin_bar, $antive;
594 $is_coming_soon_mode = antive_option( 'opt_enable_coming_soon_mode', false );
595 $disable_if_date_smaller_than_current = antive_option( 'opt_disable_coming_soon_when_date_small', false );
596
597 $coming_date = isset( $antive['opt_coming_soon_date'] ) ? $antive['opt_coming_soon_date'] : '';
598 $today = date( 'm/d/Y' );
599 if ( trim( $coming_date ) == '' || strtotime( $coming_date ) <= strtotime( $today ) ) {
600 if ( $disable_if_date_smaller_than_current && $is_coming_soon_mode ) {
601 $is_coming_soon_mode = false;
602 $menu_item_class = 'antive_coming_soon_expired';
603 if ( current_user_can( 'administrator' ) ) { // Coming soon expired
604 $date = isset( $antive['opt_coming_soon_date'] ) ? $antive['opt_coming_soon_date'] : date();
605 $args = array(
606 'id' => 'antive_coming_soon',
607 'parent' => 'top-secondary',
608 'title' => esc_html__( 'Coming Soon Mode Expired', 'antive' ),
609 'href' => esc_url( admin_url( 'themes.php?page=antive_options' ) ),
610 'meta' => array(
611 'class' => 'antive_coming_soon_expired',
612 'title' => esc_html__( 'Coming soon mode is actived but expired', 'antive' ),
613 ),
614 );
615 $wp_admin_bar->add_menu( $args );
616 }
617 }
618 }
619 if ( current_user_can( 'administrator' ) && $is_coming_soon_mode ) {
620 $date = isset( $antive['opt_coming_soon_date'] ) ? $antive['opt_coming_soon_date'] : date();
621 $args = array(
622 'id' => 'antive_coming_soon',
623 'parent' => 'top-secondary',
624 'title' => esc_html__( 'Coming Soon Mode', 'antive' ),
625 'href' => esc_url( admin_url( 'themes.php?page=antive_options' ) ),
626 'meta' => array(
627 'class' => 'antive_coming_soon antive-countdown-wrap countdown-admin-menu antive-cms-date_' . esc_attr( $date ),
628 'title' => esc_html__( 'Coming soon mode is actived', 'antive' ),
629 ),
630 );
631 $wp_admin_bar->add_menu( $args );
632 }
633
634 }
635
636 add_action( 'wp_before_admin_bar_render', 'antive_coming_soon_mode_admin_toolbar', 999 );
637}
638if ( ! function_exists( 'antive_wp_title' ) ) {
639 /*
640 * WP title
641*/
642 function antive_wp_title( $title, $separator ) {
643 global $antive;
644 if ( is_feed() ) {
645 return $title;
646 }
647 $is_coming_soon_mode = isset( $antive['opt_enable_coming_soon_mode'] ) ? $antive['opt_enable_coming_soon_mode'] == '1' : false;
648 if ( ! current_user_can( 'administrator' ) && $is_coming_soon_mode ) {
649 $title = isset( $antive['opt_coming_soon_site_title'] ) ? $antive['opt_coming_soon_site_title'] : $title;
650 } else {
651 return $title;
652 }
653
654 return $title;
655 }
656
657 add_filter( 'wp_title', 'antive_wp_title', 10, 2 );
658
659}
660if ( ! function_exists( 'antive_custom_data_js' ) ) {
661 function antive_custom_data_js() {
662 $data = array();
663 // Get option for permalink
664 $data['permalink'] = ( get_option( 'permalink_structure' ) == '' ) ? 'plain' : '';
665
666 return $data;
667 }
668}
669
670if ( ! function_exists( 'antive_img_lazy' ) ) {
671 function antive_img_lazy( $width = 1, $height = 1 ) {
672 // $img_lazy = 'data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20viewBox%3D%270%200%20' . $width . '%20' . $height . '%27%2F%3E';
673 // $img_lazy = 'https://via.placeholder.com/' . $width . 'x' . $height . '/fff/fff';
674 $img_lazy = antive_no_image(
675 array(
676 'width' => $width,
677 'height' => $height
678 ), false, true );
679
680 return $img_lazy;
681 }
682}
683
684if ( ! function_exists( 'antive_img_output' ) ) {
685 /**
686 * @param array $img
687 * @param string $class
688 * @param string $alt
689 * @param string $title
690 *
691 * @return string
692 */
693 function antive_img_output( $img, $class = '', $alt = '', $title = '' ) {
694
695 $img_default = array(
696 'width' => '',
697 'height' => '',
698 'url' => ''
699 );
700 $img = wp_parse_args( $img, $img_default );
701 $antive_enable_lazy = antive_option( 'antive_enable_lazy', false );
702
703 if ( $antive_enable_lazy ) {
704 $img_lazy = antive_img_lazy( $img['width'], $img['height'] );
705 $img_html = '<img class="fami-img fami-lazy lazy ' . esc_attr( $class ) . '" width="' . esc_attr( $img['width'] ) . '" height="' . esc_attr( $img['height'] ) . '" src="' . $img_lazy . '" data-src="' . esc_url( $img['url'] ) . '" alt="' . esc_attr( $alt ) . '" title="' . esc_attr( $title ) . '" />';
706 } else {
707 $img_html = '<img class="fami-img ' . esc_attr( $class ) . '" width="' . esc_attr( $img['width'] ) . '" height="' . esc_attr( $img['height'] ) . '" src="' . esc_url( $img['url'] ) . '" alt="' . esc_attr( $alt ) . '" title="' . esc_attr( $title ) . '" />';
708 }
709
710 return $img_html;
711 }
712}
713add_action( 'admin_head', 'vc_css_admin' );
714if ( ! function_exists( 'vc_css_admin' ) ) {
715 function vc_css_admin() {
716 echo '<style>
717 .vc_license-activation-notice {
718 display:none;
719 }
720 </style>';
721 }
722}
723
724add_action('wp_ajax_wdm_add_user_custom_data_options', 'wdm_add_user_custom_data_options_callback');
725add_action('wp_ajax_nopriv_wdm_add_user_custom_data_options', 'wdm_add_user_custom_data_options_callback');
726
727function wdm_add_user_custom_data_options_callback()
728{
729 //Custom data - Sent Via AJAX post method
730 $product_id = $_POST['id']; //This is product ID
731 $user_custom_data_values = $_POST['user_data']; //This is User custom value sent via AJAX
732 session_start();
733
734 $_SESSION['wdm_user_custom_data'] = $user_custom_data_values;
735 die();
736}
737
738add_filter('woocommerce_add_cart_item_data','wdm_add_item_data',1,2);
739
740if(!function_exists('wdm_add_item_data'))
741{
742 function wdm_add_item_data($cart_item_data,$product_id)
743 {
744 /*Here, We are adding item in WooCommerce session with, wdm_user_custom_data_value name*/
745 global $woocommerce;
746 session_start();
747 if (isset($_SESSION['wdm_user_custom_data'])) {
748 $option = $_SESSION['wdm_user_custom_data'];
749 $new_value = array('wdm_user_custom_data_value' => $option);
750 }
751 if(empty($option))
752 return $cart_item_data;
753 else
754 {
755 if(empty($cart_item_data))
756 return $new_value;
757 else
758 return array_merge($cart_item_data,$new_value);
759 }
760 unset($_SESSION['wdm_user_custom_data']);
761 //Unset our custom session variable, as it is no longer needed.
762 }
763}
764
765
766add_filter('woocommerce_get_cart_item_from_session', 'wdm_get_cart_items_from_session', 1, 3 );
767if(!function_exists('wdm_get_cart_items_from_session'))
768{
769 function wdm_get_cart_items_from_session($item,$values,$key)
770 {
771 if (array_key_exists( 'wdm_user_custom_data_value', $values ) )
772 {
773 $item['wdm_user_custom_data_value'] = $values['wdm_user_custom_data_value'];
774 }
775 return $item;
776 }
777}
778
779add_filter('woocommerce_checkout_cart_item_quantity','wdm_add_user_custom_option_from_session_into_cart',1,3);
780add_filter('woocommerce_cart_item_price','wdm_add_user_custom_option_from_session_into_cart',1,3);
781if(!function_exists('wdm_add_user_custom_option_from_session_into_cart'))
782{
783 function wdm_add_user_custom_option_from_session_into_cart($product_name, $values, $cart_item_key )
784 {
785 /*code to add custom data on Cart & checkout Page*/
786 if(count($values['wdm_user_custom_data_value']) > 0)
787 {
788 $return_string = $product_name . "</a><dl class='variation'>";
789 $return_string .= "<table class='wdm_options_table' id='" . $values['product_id'] . "'>";
790 $return_string .= "<tr><td>" . $values['wdm_user_custom_data_value'] . "</td></tr>";
791 $return_string .= "</table></dl>";
792 return $return_string;
793 }
794 else
795 {
796 return $product_name;
797 }
798 }
799}
800
801add_action('woocommerce_add_order_item_meta','wdm_add_values_to_order_item_meta',1,2);
802if(!function_exists('wdm_add_values_to_order_item_meta'))
803{
804 function wdm_add_values_to_order_item_meta($item_id, $values)
805 {
806 global $woocommerce,$wpdb;
807 $user_custom_values = $values['wdm_user_custom_data_value'];
808 if(!empty($user_custom_values))
809 {
810 wc_add_order_item_meta($item_id,'wdm_user_custom_data',$user_custom_values);
811 }
812 }
813}
814
815add_action('woocommerce_add_order_item_meta','wdm_add_values_to_order_item_meta',1,2);
816if(!function_exists('wdm_add_values_to_order_item_meta'))
817{
818 function wdm_add_values_to_order_item_meta($item_id, $values)
819 {
820 global $woocommerce,$wpdb;
821 $user_custom_values = $values['wdm_user_custom_data_value'];
822 if(!empty($user_custom_values))
823 {
824 wc_add_order_item_meta($item_id,'wdm_user_custom_data',$user_custom_values);
825 }
826 }
827}
828//add_action( 'woocommerce_order_status_completed', 'wc_send_order_to_mypage' );
829function wc_send_order_to_mypage( $order_id ) {
830$shipping_add = [
831 "firstname" => $order->shipping_first_name,
832 "lastname" => $order->shipping_last_name,
833 "address1" => $order->shipping_address_1,
834 "address2" => $order->shipping_address_2,
835 "city" => $order->shipping_city,
836 "zipcode" => $order->shipping_postcode,
837 "phone" => $order->shipping_phone,
838 "state_name" => $order->shipping_state,
839 "country" => $order->shipping_country
840 ];
841//from $order you can get all the item information etc
842//above is just a simple example how it works
843//your code to send data
844}
845
846//add_action( 'woocommerce_thankyou', 'MyPersistRemoteObject3', 10, 1 );
847
848function MyPersistRemoteObject3($order_id){
849
850$ch = curl_init();
851 curl_setopt_array($ch, array(
852 CURLOPT_URL => "http://52.6.107.225/script.php?order_id=" . $order_id,
853 CURLOPT_RETURNTRANSFER => true,
854 CURLOPT_ENCODING => "",
855 CURLOPT_MAXREDIRS => 10,
856 CURLOPT_TIMEOUT => 30,
857 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
858 CURLOPT_CUSTOMREQUEST => "GET",
859 CURLOPT_SSL_VERIFYPEER=> false,
860
861 CURLOPT_HTTPHEADER => array(
862 "Authorization: Basic *****************",
863 "Cache-Control: no-cache"
864 ),
865 ));
866
867 $result = curl_exec($ch);
868
869 // Get an instance of the WC_Order object
870 $order = wc_get_order($order_id);
871 $collection = getProdutosForWikiWs();
872 // Iterating through each WC_Order_Item_Product objects
873 foreach ($order->get_items() as $item_key => $item ):
874
875 ## Using WC_Order_Item methods ##
876 // Item ID is directly accessible from the $item_key in the foreach loop or
877 $item_id = $item->get_id();
878 $product = $item->get_product(); // Get the WC_Product object
879 $product_id = $item->get_product_id(); // the Product id
880 $product_sku = $product->get_sku();
881 $title = $item->get_title();
882
883
884foreach($collection as $k=>$wsCollection){
885 if($wsCollection->produtoId == $product_sku){
886 //update_post_meta($product_id,'_sku',$product_sku);
887 }
888 else{
889 //update_post_meta($product_id,'_sku',"not_sku:" . $title);
890 }
891}
892
893endforeach;
894
895 //var_dump($result);
896 //echo "<pre>";
897 //var_dump( curl_getinfo($ch) ) . '<br/>';
898 //echo curl_errno($ch) . '<br/>';
899 //echo curl_error($ch) . '<br/>';
900}
901
902
903
904add_filter( 'woocommerce_rest_check_permissions', 'my_woocommerce_rest_check_permissions', 90, 4 );
905function my_woocommerce_rest_check_permissions( $permission, $context, $object_id, $post_type ){
906 return true;
907}
908
909
910
911function updateAllSku(){
912 FavelaMigration::init();
913 exit;
914
915 $arquivo = fopen('logs.txt','w');
916 //verificamos se foi criado
917 if ($arquivo == false) die('Não foi possível criar o arquivo.');
918 //escrevemos no arquivo
919 $params = array(
920 'posts_per_page' => 300,
921 'post_type' => 'product'
922 );
923
924 $wc_query = new WP_Query($params);
925 $favchikObjects = $wc_query->posts;
926 //157 item total woo //135 sku correto // (22 com referencia errada) | 30 novos items (total com problema 52)
927
928 foreach($favchikObjects as $k=>$fobj){
929 $prod = wc_get_product($fobj->ID);
930
931 //echo "sku base: " . $prod->get_sku() ."<br>";
932
933 }
934
935 $collection = getProdutosForWikiWs();
936// print_r($collection);
937 $totalWsProducts = count($collection);
938 $c = 0;
939 //187 items (total wiki)
940 foreach($collection as $product => $p){
941 //135 items aqui
942 $_product_id = wc_get_product_id_by_sku($p->produtoId);
943
944 if ( $_product_id != "" ) {
945 $produtosComSku[] = $_product_id;
946 //Get an instance of the WC_Product Object
947 $_product[] = wc_get_product($_product_id);
948 //fwrite($arquivo, "sku exists: product_id:{$_product_id} | ws_productId:{$p->produtoId} | sku: {$_product->get_sku()}");
949 //update_post_meta($_product_id,'_sku',$p->produtoId, $_product->get_sku());
950 }else{
951 //52 items com problema aqui (produtos com problema e novos produtos)
952 $skuproblem[] = $collection[$c];
953 //$productObj[] = get_title(html_entity_decode($collection[$c]->produtoNome . ',' . $collection[$c]->produtoMarca));
954 //6 items achados = total de 46 items com problema = 24 items com referencia errada
955 $productObj[] = get_wc_product_by_title($collection[$c]->produtoNome, $collection[$c]->produtoMarca);
956 $idsDeProdutosComProblema[] = $_product_id;
957
958
959 //var_dump($productObj);
960 //{produtoNome[1]}, {produtoMarca[1]}
961
962 //$_product = wc_get_product($p->produtoId);
963 //fwrite($arquivo, "sku not exists: product_id:{$_product_id} | ws_productId:{$p->produtoId}");
964 //update_post_meta($_product_id,'_sku',$p->produtoId);
965 }
966 $c++;
967 }
968
969 //echo "ids de produtos com problemas";
970 //print_r($idsDeProdutosComProblema);
971
972 //total de objetos percorre todos os ids que existem
973 echo "total de produtos com sku: ";
974 echo count($_product) . "<br>";
975
976 echo "total de produtos Direto do Banco: ";
977 echo count($favchikObjects) . "<br>";
978
979 //157 objeto
980 $j = 0;
981 foreach($favchikObjects as $l=>$fav){
982 $favchickcoll[] = wc_get_product($fav->ID);
983 foreach($_product as $p=>$prod){
984 if($prod->get_sku() == $favchickcoll[$l]->get_sku()){
985 $newfavArray[] = $favchickcoll;
986 //unset($favchickcoll[$l]);
987 echo "key[1] : {[$j]}: {$prod->get_id()} ";
988 $j++;
989 }elseif($prod->get_id() != $favchickcoll[$l]->get_id()){
990 //unset($favchickcoll[$l]);
991 //echo " | key[3] : {[$l]}: {$favchickcoll[$l]->get_id()}<br>";
992 }
993 }
994
995 echo " | key[2] : {[$l]}: {$favchickcoll[$l]->get_id()}<br>";
996 //echo " | : {[$l]}: {$newfavArray[$l][$l]->get_id()}<br>";
997 //print_r($newfavArray);
998 }
999
1000
1001 //135
1002 echo "sku identicos | ";
1003 var_dump(count($newfavArray));
1004
1005 //135
1006 echo "sku não bate | ";
1007 print_r(count($favchickcoll)) . "<br>";
1008
1009 exit;
1010 for($i=0;$i<count($_product); $i++){
1011 //echo $i ."<br>";
1012 $favchickcoll[$i] = wc_get_product($favchikObjects[$i]->ID);
1013
1014 if($favchickcoll[$i]->get_sku() == $_product[$i]->get_sku()){
1015
1016 $arrayIdExists[] = $favchikObjects[$i];
1017 }else{
1018 //echo $_product[$i]->get_sku() . " | : " . $favchickcoll[$i]->get_sku() . "<br>";
1019 $arrayIdNotExists[] = $favchikObjects[$i];
1020 unset($favchikObjects[$i]);
1021 }
1022 }
1023
1024
1025 echo "resto dos produtos sem sku correto - ";
1026 print_r(count($favchikObjects));
1027
1028
1029
1030 echo " Total de produtos com SKU correto: ";
1031 print_r(count($produtosComSku));
1032
1033 echo " | Total de produtos do WebService: ";
1034 print_r($totalWsProducts) . "<br>";
1035
1036
1037 echo " | produtos achados na busca por titulo/marca ";
1038 echo(count($productObj));
1039
1040 foreach($productObj as $k=>$obj){
1041 if(!empty($obj)){
1042 $produtosBuscadosPeloTitulo[] = $obj;
1043 //var_dump($obj->get_title());
1044 }
1045 }
1046
1047 echo " | produtos com títulos que batem com o web service ";
1048 print_r(count($produtosBuscadosPeloTitulo));
1049
1050 echo " | Total de produtos sem sku correto ";
1051 print_r(count($skuproblem) -count($produtosBuscadosPeloTitulo) ) . "<br>";
1052
1053 //echo " | Resto dos produtos com problema (só titulo)";
1054
1055 //global $postTitle;
1056 //var_dump($postTitle);
1057
1058 echo " | Resto dos produtos com problema (Objetos) Vindos do Wiki ";
1059 print_r(count($skuproblem));
1060 /*
1061 foreach($skuproblem as $k=>$pobj){
1062
1063 var_dump($pobj->produtoId);
1064
1065 }*/
1066
1067 /*
1068 echo " | Total de produtos da loja - ";
1069 print_r(count($favchikObjects));
1070
1071
1072 echo " | skuExists - ";
1073 print_r(count($arrayIdExists));
1074
1075 echo " | skuNotExists - ";
1076 print_r(count($arrayIdNotExists));
1077 */
1078 exit;
1079}
1080
1081function get_wc_product_by_title( $title, $post_marca){
1082 global $wpdb;
1083 global $postTitle;
1084
1085 $post_title = urldecode(strval($title));
1086 $post_marca = urldecode(strval($post_marca));
1087 $postTitle[] = $post_title;
1088
1089 $title_name_marca = $post_title . ", ". $post_marca;
1090
1091 //echo "IMPRIMINDO OS TÍTULOS PASSADOS PELO WS";
1092 //var_dump($postTitle);
1093
1094 $post_table = $wpdb->prefix . "posts";
1095 $result = $wpdb->get_col(
1096 "SELECT
1097 posts.ID, posts.post_title
1098 FROM wp_posts AS posts INNER JOIN wp_term_relationships AS term_relationships
1099 ON posts.ID = term_relationships.object_id INNER JOIN wp_term_taxonomy AS term_taxonomy
1100 ON term_relationships.term_taxonomy_id = term_taxonomy.term_taxonomy_id
1101 INNER JOIN wp_terms AS terms
1102 ON term_taxonomy.term_id = terms.term_id
1103 WHERE term_taxonomy.taxonomy = 'product_type'
1104 AND posts.post_title LIKE '%$title_name_marca%'
1105 AND posts.post_type = 'product'"
1106 );
1107
1108 //var_dump($post_title);
1109 //var_dump($result);
1110 // We exit if title doesn't match
1111 $result2 = $wpdb->get_col(
1112 "SELECT
1113 posts.ID, posts.post_title
1114 FROM wp_posts AS posts INNER JOIN wp_term_relationships AS term_relationships
1115 ON posts.ID = term_relationships.object_id INNER JOIN wp_term_taxonomy AS term_taxonomy
1116 ON term_relationships.term_taxonomy_id = term_taxonomy.term_taxonomy_id
1117 INNER JOIN wp_terms AS terms
1118 ON term_taxonomy.term_id = terms.term_id
1119 WHERE term_taxonomy.taxonomy = 'product_type'
1120 AND posts.post_status NOT IN('trash')
1121 AND posts.post_title LIKE '%$title_name_marca%'
1122 AND posts.post_type = 'product'"
1123 );
1124
1125 if(empty($result2[0])){
1126 return;
1127 }
1128 else{
1129
1130 //var_dump($result2[0]);
1131 }
1132
1133 if( empty( $result[0] ) )
1134 return;
1135 else
1136 //print_r(wc_get_product( intval( $result[0])));
1137 return wc_get_product( $result2[0] );
1138}
1139
1140
1141
1142function getProdutosForWikiWs(){
1143 /*
1144 $ch = curl_init();
1145 curl_setopt_array($ch, array(
1146 CURLOPT_URL => "http://52.6.107.225/script.php?ws=produtos",
1147 CURLOPT_RETURNTRANSFER => true,
1148 CURLOPT_ENCODING => "",
1149 CURLOPT_MAXREDIRS => 10,
1150 CURLOPT_TIMEOUT => 30,
1151 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
1152 CURLOPT_CUSTOMREQUEST => "GET",
1153 CURLOPT_SSL_VERIFYPEER=> false,
1154
1155 CURLOPT_HTTPHEADER => array(
1156 "Authorization: Basic *****************",
1157 "Cache-Control: no-cache"
1158 ),
1159 ));
1160
1161 $result = curl_exec($ch);
1162 */
1163 $collection = json_decode(_getJson());
1164 //$collection = json_decode($result);
1165 return $collection;
1166
1167
1168 //curl_close($ch);
1169 }
1170
1171/*
1172//usage
1173$parent_id = 746; // Or get the variable product id dynamically
1174
1175//The variation data
1176$variation_data = array(
1177 'attributes' => array(
1178 'size' => 'M',
1179 'color' => 'Green',
1180 ),
1181 'sku' => '',
1182 'regular_price' => '22.00',
1183 'sale_price' => '',
1184 'stock_qty' => 10,
1185);
1186
1187// The function to be run
1188create_product_variation( $parent_id, $variation_data );
1189*/
1190
1191function insertSimpleProduct(){
1192 $post = array(
1193 'post_author' => $user_id,
1194 'post_content' => '',
1195 'post_status' => "publish",
1196 'post_title' => $product->part_num,
1197 'post_parent' => '',
1198 'post_type' => "product",
1199 );
1200
1201 //Create post
1202 $post_id = wp_insert_post( $post, $wp_error );
1203 if($post_id){
1204 $attach_id = get_post_meta($product->parent_id, "_thumbnail_id", true);
1205 add_post_meta($post_id, '_thumbnail_id', $attach_id);
1206 }
1207
1208 wp_set_object_terms( $post_id, 'Races', 'product_cat' );
1209 wp_set_object_terms( $post_id, 'simple', 'product_type');
1210
1211 update_post_meta( $post_id, '_visibility', 'visible' );
1212 update_post_meta( $post_id, '_stock_status', 'instock');
1213 update_post_meta( $post_id, 'total_sales', '0');
1214 update_post_meta( $post_id, '_downloadable', 'yes');
1215 update_post_meta( $post_id, '_virtual', 'yes');
1216 update_post_meta( $post_id, '_regular_price', "1" );
1217 update_post_meta( $post_id, '_sale_price', "1" );
1218 update_post_meta( $post_id, '_purchase_note', "" );
1219 update_post_meta( $post_id, '_featured', "no" );
1220 update_post_meta( $post_id, '_weight', "" );
1221 update_post_meta( $post_id, '_length', "" );
1222 update_post_meta( $post_id, '_width', "" );
1223 update_post_meta( $post_id, '_height', "" );
1224 update_post_meta( $post_id, '_sku', "");
1225 update_post_meta( $post_id, '_product_attributes', array());
1226 update_post_meta( $post_id, '_sale_price_dates_from', "" );
1227 update_post_meta( $post_id, '_sale_price_dates_to', "" );
1228 update_post_meta( $post_id, '_price', "1" );
1229 update_post_meta( $post_id, '_sold_individually', "" );
1230 update_post_meta( $post_id, '_manage_stock', "no" );
1231 update_post_meta( $post_id, '_backorders', "no" );
1232 update_post_meta( $post_id, '_stock', "" );
1233}
1234
1235add_action( 'woocommerce_thankyou', 'initMigration', 20, 2 );
1236
1237function initMigration(){
1238 /*
1239 for($i=0;$i<=186;$i++){
1240 //FavelaMigration::init($prodPosition=185);
1241 echo "no loop: {$i}";
1242 FavelaMigration::init($i);
1243 }
1244 return;*/
1245 //pega todos os dados do WS
1246 $collection = getProdutosForWikiWs();
1247 //cria um array de nomes remotos
1248
1249 $totalRemoteP = count($collection);
1250
1251 for($i=0;$i <= count($collection);$i++){
1252 //FavelaMigration::init($prodPosition=185);
1253 echo "no loop: {$i} [{$totalRemoteP}]";
1254 FavelaMigration::init($i);
1255 }
1256
1257
1258 $remoteName = [];
1259 foreach($collection as $cln=>$coll){
1260 $remoteName[] = "{$coll->produtoNome}, {$coll->produtoMarca}";
1261 }
1262
1263 #inicializa variáveis de operacao
1264 //variaveis locais
1265 $localProducts = FavelaMigration::getAllLocalProducts();
1266 //var_dump($localProducts);
1267 $notExistsProduct = [];
1268 //total de ids (local/remoto)
1269 $totalIds = [];
1270 $idsQDiferetem = [];
1271 $idsQBatem = [];
1272 $totalNames = [];
1273 $remoteSlug = new stdClass;
1274 $remoteProductSku = new stdClass;
1275 $localSlugs = new stdClass;
1276 $localProductName = new stdClass;
1277 $rmNames = [];
1278 $lcNames = [];
1279 $localProductName->name = [];
1280 $countIdsQDiferem = 0;
1281
1282 foreach($localProducts as $k=>$lp){
1283 foreach($collection as $c=>$cl){
1284 $resultSearch = FavelaMigration::searchProduct($cl);
1285
1286 if(empty($resultSearch)){
1287 $notExistsProduct[] = $resultSearch;
1288 }else{
1289 //Se existe na base local um produto correspondente ao remoto.
1290 $produtoName[$c] = "{$cl->produtoNome}, {$cl->produtoMarca}";
1291 $productSlug[$c] = $resultSearch->get_slug();
1292 $totalIds[] = $resultSearch->get_id();
1293 $remoteSlug->slug[] = $resultSearch->get_slug();
1294 $localSlugs->slug[] = $lp->get_slug();
1295 $remoteProductSku->sku[] = $resultSearch->get_sku();
1296 $localProductName->name[] = "{$lp->get_name()}, {$cl->produtoMarca}";
1297 }
1298 // && $remoteProductSku->sku[$c] == $lp->get_sku()
1299 if($lp->get_slug() == $remoteSlug->slug[$c]){
1300 echo "*Produto(Local) Nome:{$lp->get_name()}, id:{$lp->get_id()}, slug:{$lp->get_slug()},
1301 c:({$c}), sku:{$lp->get_sku()} Produto(Remoto): Nome:{$produtoName[$c]},
1302 slug:{$productSlug[$c]} ,sku:{$remoteProductSku->sku[$c]} status:[Bate com o WS
1303 id:{$totalIds[$c]}] <br>";
1304
1305
1306 echo "(ids iguais)k: {$c} | : (remotos)" . ($totalIds[$c]) . " (locais): {$lp->get_id()}<br>";
1307 $idsQBatem[] = $lp->get_id();
1308 $totalNames[] = $resultSearch->get_name();
1309 $rmNames[] = ['name'=>$remoteName[$c], 'slug'=>$remoteSlug->slug[$c],'id'=>$totalIds[$c], 'sku'=>$remoteProductSku->sku];
1310 $lcNames[] = ['name'=>$lp->get_name(), 'slug'=>$lp->get_slug(),'id'=>$lp->get_id(), 'sku'=>$lp->get_sku()];
1311
1312 }
1313 else{
1314 echo "-Produto(Local) Nome:{$lp->get_name()}, id:{$lp->get_id()}, slug:{$lp->get_slug()},
1315 c:({$c}), sku:{$lp->get_sku()} Produto(Remoto): Nome:{$produtoName[$c]},
1316 slug:{$productSlug[$c]} ,sku:{$remoteProductSku->sku[$c]}
1317 status:[Não Bate com o WS id:{$totalIds[$c]}] <br>";
1318
1319 echo "(ids Diferem)k: {$c} | : (remotos)" . ($totalIds[$c]) . " (locais): {$lp->get_id()}<br>";
1320 $idsQDiferetem[] = $lp->get_id();
1321 }
1322 }
1323 }
1324
1325
1326 echo "<br><b>ids Que Batem</b><br>";
1327 var_dump(count($idsQBatem));
1328 print_r($idsQBatem);
1329
1330 echo "<b>Total Ids do WebService</b><br>";
1331 //var_dump(count($totalIds));
1332 echo "<b>Total Ids Não batem com a busta de Texto</b><br>";
1333 var_dump(count($notExistsProduct));
1334
1335 echo "<b>Ids que diferem</b><br>";
1336 $result = array_unique($idsQDiferetem);
1337 //print_r($result);
1338 var_dump(count($result));
1339 print_r($result);
1340
1341 echo "<b>Diff dos 2 arrays(ids)</b><br>";
1342 //Ids que diferem | ids que batem
1343 $diffResult = array_diff($result, $idsQBatem);
1344
1345 var_dump(count($diffResult));
1346 //var_dump($diffResult);
1347
1348 echo "<b>Produtos do Diff</b><br>";
1349 print_r($diffResult);
1350 $deletedIds = $diffResult;
1351
1352/*
1353 echo "<b>Diff das Slugs</b><br>";
1354 $diffResultSlugs = array_diff($localSlugs->slug, $remoteSlug->slug);
1355 $resultSlug = array_unique($diffResultSlugs);
1356
1357 var_dump(count($diffResultSlugs));
1358 //print_r($diffResultSlugs);
1359 echo "<b>Slug processado excluido os Repetidos</b><br>";
1360 var_dump(count($resultSlug));
1361 //var_dump($resultSlug);
1362 //var_dump($diffResultSlugs);
1363
1364
1365 echo " <b>Diff dos Nomes(locais/remotos)</b><br>";
1366 $diffResultNames = array_diff($totalNames, $remoteName);
1367 var_dump(count($diffResultNames));
1368 //print_r($diffResultNames);
1369 echo "<b>Total de nomes que Batem</b><br>";
1370 var_dump(count($totalNames));
1371
1372 echo "<b>Total de nomes do Ws</b><br>";
1373 var_dump(count($remoteName));
1374
1375 echo "<b>Remote Info Produtcs{names}</b><br>";
1376 var_dump(count($rmNames));
1377 //print_r($rmNames);
1378
1379 echo "<b>Local Info Produtcs{names}</b><br>";
1380 var_dump(count($lcNames));
1381 //print_r($lcNames);
1382 //print_r($diffResultNames);
1383*/
1384 if(isset($deletedIds)){
1385 $productNameDelIds = [];
1386 foreach($deletedIds as $d => $pDelete){
1387 $product = wc_get_product($pDelete);
1388 $productNameDelIds[] = $product->get_name();
1389 echo "Produto Não Corresponde a API Enviado para a Lixeira id[{$pDelete} | nome: {$productNameDelIds[$d]}]<br>";
1390 //wh_deleteProduct($pDelete);
1391 $product = wc_get_product($pDelete);
1392 $product->delete();
1393 $result = 'trash' === $product->get_status();
1394
1395 if (!$result)
1396 {
1397 return new WP_Error(999, sprintf(__('This %s cannot be deleted', 'woocommerce'), 'product'));
1398 }
1399 }
1400 }
1401
1402
1403
1404
1405 //61
1406 //FavelaMigration::init($prodPosition=61);
1407 //186
1408 /*
1409 $bate = 0;
1410 foreach($collection as $k=> $coll){
1411
1412 //FavelaMigration::init($prodPosition=185);
1413 //echo "no loop: {$i}";
1414 //$productsOp[] = FavelaMigration::init($i);
1415
1416 $productTeste = $coll;
1417 $resultSearch = FavelaMigration::searchProduct($productTeste);
1418 if(empty($resultSearch)){
1419 echo "<h4>Produto não existe na base Local</h4>";
1420
1421 }else{
1422 $totalIds[] = $resultSearch->get_id();
1423 //echo "<h4>Produto existe na base Local</h2>";
1424 //var_dump($resultSearch);
1425 }
1426
1427 $produtoName = "{$coll->produtoNome}, {$coll->produtoMarca}";
1428
1429 foreach($totalIds as $t=>$tIds){
1430 if($localProducts[$t]->get_id() == $tIds){
1431 echo "*Produto(Local) Nome:{$localProducts[$k]->get_name()}, id:{$localProducts[$k]->get_id()} ({$k}) Produto(Remoto)Nome:$produtoName [Bate com o WS (id:{$tIds})] Bate: [{$bate}]<br>";
1432 $bate++;
1433 //echo "(ids iguais) k: {$k} | t: [{$t}] : ids remoto: " . ($tIds) . " ids local: {$localProducts[$t]->get_id()} <br>";
1434 echo "(ids iguais)k: {$k} | t: [{$t}] : (remotos)" . ($tIds) . " (locais): {$localProducts[$t]->get_id()}<br>";
1435 //unset($lp);
1436 //$listVerify['produtoBate'] = $localProducts[$prodPosition];
1437 //$listNoExists = $lp;
1438 }else{
1439
1440 //echo "*Produto(Local) Nome:{$localProducts[$k]->get_name()}, id:{$localProducts[$i]->get_id()}[c:{$i}] ({$i}) Produto(Remoto)Nome:$produtoName [Não Bate com o WS (id:{$totalIds[0]})]<br>";
1441
1442 //unset($localProducts);
1443 echo "(ids diferentes)k: {$k} | t: [{$t}] : (remotos)" . ($tIds) . " (locais): {$localProducts[$t]->get_id()}<br>";
1444 }
1445 }
1446
1447 //echo "<h4>Total de produtos Locais</h4>";
1448
1449
1450 }*/
1451
1452 //print_r($listVerify);
1453 //print_r($totalIds);
1454
1455
1456 //return $listVerify;
1457
1458
1459
1460 //echo "<h4>Produtos Operacionais</h4>";
1461 //print_r($productsOp);
1462 //var_dump($productsOp["produtoBate"]);
1463}
1464
1465class MigrationRules {
1466
1467 private static $lproduct, $rproduct, $collection,
1468 $postId, $prodPosition, $productTeste, $remoteAttr;
1469
1470 private static $tamanhoUpdated = false;
1471 private static $isUpdated = false;
1472
1473 static function filterVariations($post_id,$meta_key,$meta_value) {
1474 $query = new \WP_Query( array(
1475 'post_parent' => $post_id,
1476 'post_status' => 'publish',
1477 'post_type' => 'product_variation',
1478 'posts_per_page' => -1,
1479 'meta_query' => array( array(
1480 'key' => $meta_key,
1481 'value' => $meta_value,
1482 ) ),
1483 ) );
1484 $result = array();
1485 if($query->have_posts()){
1486 while ($query->have_posts()) {
1487 $query->next_post();
1488 $result[] = $query->post;
1489 }
1490 wp_reset_postdata();
1491 }
1492 wp_reset_query();
1493
1494 return $result;
1495 }
1496/*
1497*
1498
1499**/
1500 static function _filterVariations($post_id,array $properties) {
1501 $query = new \WP_Query( array(
1502 'post_parent' => $post_id,
1503 'post_status' => 'publish',
1504 'post_type' => 'product_variation',
1505 'posts_per_page' => -1,
1506 'meta_query' => array(
1507 'relation' => 'AND',
1508 'cor_clause' => array(
1509 'key' => $properties['cor_key'],
1510 'value' => $properties['cor_value'],
1511 ),
1512 'tamanho_clause' => array(
1513 'key' => $properties['tamanho_key'],
1514 'value' => $properties['tamanho_value'],
1515 ),
1516 ),
1517 ) );
1518 $result = array();
1519 if($query->have_posts()){
1520 while ($query->have_posts()) {
1521 $query->next_post();
1522 $result[] = $query->post;
1523 }
1524 wp_reset_postdata();
1525 }
1526 wp_reset_query();
1527
1528 return $result;
1529 }
1530
1531 static function storeStock($listCorT, $x){
1532 $rtotal = self::getTotalRemoteProducts(); //trata os dados do estoque
1533
1534 if(strlen($listCorT->produtoQtdeEstoque) <= 4){
1535 $_stockRemote = (int)substr($listCorT->produtoQtdeEstoque,0,1);
1536 } else{
1537 $_stockRemote = (int)substr($listCorT->produtoQtdeEstoque,0,2);
1538 }
1539
1540 echo "{Cor:[{$listCorT->produtoCor}], Tamanho:[{$listCorT->produtoTamanho}] Será persistido} | (x:{$x},total:{$rtotal}) | <br>";
1541 $variation_data = [
1542 'attributes' => [
1543 'cor' => $listCorT->produtoCor,
1544 'tamanho' => $listCorT->produtoTamanho,
1545 ],
1546 'sku' => MigrationRules::getProductTeste()->produtoId,
1547 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1548 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1549 'stock_qty' => $_stockRemote
1550 ];
1551 // The function to be run
1552 _create_product_variation(MigrationRules::getPostId(), $variation_data );
1553 }
1554
1555 static function updateStock($listCorT, $attrCor, $attrTamanho, $attrStock, $x, $c, $cproducts){
1556 $rtotal = self::getTotalRemoteProducts(); //trata os dados do estoque
1557 $totalL = self::getTotalLocalProducts();
1558 $diffProducts = $rtotal-$totalL;
1559
1560 if(strlen($listCorT->produtoQtdeEstoque) <= 4){
1561 $_stockRemote = (int)substr($listCorT->produtoQtdeEstoque,0,1);
1562 } else{
1563 $_stockRemote = (int)substr($listCorT->produtoQtdeEstoque,0,2);
1564 }
1565
1566 $pcor = strtolower(tirarAcentos($listCorT->produtoCor));
1567 $acor = strtolower(tirarAcentos($attrCor));
1568
1569 $corFragment = explode(" ", $pcor);
1570
1571 if(isset($corFragment[0])){
1572 $pcor = $corFragment[0];
1573 }
1574
1575 if(isset($corFragment[1])){
1576 $pcor = $corFragment[0] . "-" . $corFragment[1];
1577 }
1578
1579
1580 $rTamanho = strtolower(tirarAcentos($listCorT->produtoTamanho));
1581 $atTamanho = strtolower(tirarAcentos($attrTamanho));
1582
1583 if($pcor == $acor){
1584 //atualiza
1585 echo "produtoCor:[{$pcor}] são iguais AttrCor:[{$acor}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
1586 //se o tamanho do produto for igual
1587 if($rTamanho == $attrTamanho){
1588 //atualiza
1589 echo "produtoTamanho:[{$rTamanho}] são iguais attrTamanho:[{$atTamanho}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
1590
1591 //se o estoque remoto for igual ao estoque local (Não atualiza)
1592 if($_stockRemote == $attrStock){
1593 //não atualiza
1594 echo "produtoQtdeEstoque:[{$_stockRemote}] são iguais{NÃO ATUALIZA} attrStock:[{$attrStock}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
1595 echo "<hr><hr>";
1596 //self::$isUpdated = true;
1597 }
1598
1599 //se estoque remoto for maior que o estoque local (Atualiza)
1600 if($_stockRemote > $attrStock){
1601 //atualiza
1602 //var_dump(self::$isUpdated);
1603
1604 echo "condition:(<i>produto tem cor e tamanho iguais e estoque local menor do que o estoque remoto</i>:)
1605 ,<br> produtoQtdeEstoque(Remoto):[{$_stockRemote}] {ATUALIZA} -> attrStock:[{$attrStock}] ({$x}-{$c}) variable_id:[$cproducts] [{{$_stockRemote}} > {{$attrStock}}] <br>";
1606 $result = MigrationRules::filterVariations(MigrationRules::getPostId(), 'attribute_pa_tamanho',$rTamanho);
1607
1608 $variation_data = [
1609 'attributes' => [
1610 'cor' => $listCorT->produtoCor,
1611 'tamanho' => $listCorT->produtoTamanho,
1612 ],
1613 'ID' => $cproducts,
1614 'sku' => MigrationRules::getProductTeste()->produtoId,
1615 'update' => true,
1616 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1617 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1618 'stock_qty' => $_stockRemote
1619 ];
1620 // The function to be run
1621 _create_product_variation(MigrationRules::getPostId(), $variation_data );
1622 //self::$isUpdated = true;
1623
1624
1625 }
1626 if($_stockRemote < $attrStock){//se for diferente, atualiza com base no valor do estoque remoto
1627 //atualiza
1628 echo "produtoQtdeEstoque(Remoto):[{$_stockRemote}] {Menor do que Estoque Local - Ação: Incrementa Sobre o Stock Local o Estoque Remoto} -> attrStock(Estoque Local):[{$attrStock}] ({$x}-{$c}) variable_id:[$cproducts] [{{$_stockRemote}} < {{$attrStock}}] <br>";
1629 echo "<hr><hr>";
1630 $localStk = (int)get_post_meta($cproducts, '_stock', true );
1631 //var_dump($localStk);
1632
1633 $variation_data = [
1634 'attributes' => [
1635 'cor' => $listCorT->produtoCor,
1636 'tamanho' => $listCorT->produtoTamanho,
1637 ],
1638 'ID' => $cproducts,
1639 'sku' => MigrationRules::getProductTeste()->produtoId,
1640 'update' => true,
1641 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1642 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1643 'stock_qty' => $_stockRemote + $localStk
1644 ];
1645 // The function to be run
1646 _create_product_variation(MigrationRules::getPostId(), $variation_data );
1647 //self::$isUpdated = true;
1648
1649 }
1650 }elseif(($totalL)-1 == $c && $totalL < $rtotal){//se tamanhos são diferentes
1651 // [se a quantidade de produtos com cores iguais e tamanhos diferentes
1652 // _remotos_ forem maior que a quantidade de produtos locais (insere ou atualiza)
1653 echo "produtoTamanho:[{$rTamanho}] são diferentes attrTamanho:[{$atTamanho}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
1654 $result = MigrationRules::_filterVariations(MigrationRules::getPostId(),
1655 ['cor_key'=>'attribute_pa_cor',
1656 'cor_value'=>$pcor,'tamanho_key'=>'attribute_pa_tamanho', 'tamanho_value'=>$rTamanho
1657 ]);
1658
1659 //var_dump($result);
1660
1661 if(empty($result)){
1662 //var_dump($result);
1663 // The variation data
1664 echo "{Tamanho remoto não existe - Tamanho [{$rTamanho}] Será persistido} | (x:{$x}, c:{$c},total:{$rtotal}) - variable_id:[$cproducts] | <br>";
1665 $variation_data = [
1666 'attributes' => [
1667 'cor' => $listCorT->produtoCor,
1668 'tamanho' => $listCorT->produtoTamanho,
1669 ],
1670 'sku' => MigrationRules::getProductTeste()->produtoId,
1671 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1672 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1673 'stock_qty' => $_stockRemote
1674 ];
1675 // The function to be run
1676 _create_product_variation(MigrationRules::getPostId(), $variation_data );
1677 }
1678 else{
1679
1680 echo "{Tamanho remoto existe na base [{$rTamanho}] Não Será atualizada} | (x:{$x}, c:{$c},total:{$rtotal}) - variable_id:[$cproducts] | {$result[0]->ID} | STock:{$_stockRemote}<br>";
1681 /*$variation_data = [
1682 'attributes' => [
1683 'cor' => $listCorT->produtoCor,
1684 'tamanho' => $listCorT->produtoTamanho,
1685 ],
1686 'ID' => $cproducts,
1687 'sku' => MigrationRules::getProductTeste()->produtoId,
1688 'update' => true,
1689 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1690 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1691 'stock_qty' => $_stockRemote
1692 ];
1693 */
1694 //_create_product_variation(MigrationRules::getPostId(), $variation_data );
1695
1696
1697 }
1698 }
1699 //se a quantidade do estoque for igual
1700 //var_dump(substr($listCorT->produtoQtdeEstoque,0,1));
1701
1702 }else{//atualiza $c (contador do loop das variacoes remotas)
1703 $totalL = self::getTotalLocalProducts();
1704 $diffProducts = $rtotal-$totalL;
1705 echo "#produtoCor:[{$pcor},{$rTamanho}] são diferentes AttrCor:[{$acor},{$atTamanho}] (x:{$x}, c:{$c},total:{$rtotal}, diffP:{$diffProducts}) - variable_id:[$cproducts] | {Cor remota não existe em cores locais}<br>";
1706 //se total de variacoes locais é menor que o total de variacoes remotas
1707 //insere a variacao remota até a quantidade de variacoes locais ficar = a quantidade de variacoes
1708 //remotas
1709 //enquanto 29 <= 52 { execulta }
1710 // $c < $rtotal && $z <= $rtotal && { $z = $c; store(color); $z++;}
1711 //$z = $c;
1712 //30 == $c
1713 //se o contador de produtos locais ficar com o mesmo valor do total de produtos locais tornarem iguais
1714 //e a quantidade de produtos locais for menor que o total de produtos remotos persiste o produto remoto
1715 if(($totalL)-1 == $c && $totalL < $rtotal){
1716 //if($z <= $rtotal){
1717 //$pID = MigrationRules::getPostId();
1718 //$result = MigrationRules::filterVariations(MigrationRules::getPostId(), 'attribute_pa_cor',$pcor);
1719 //$resultT = MigrationRules::filterVariations(MigrationRules::getPostId(), 'attribute_pa_tamanho',$listCorT->produtoTamanho);
1720 //echo "produtoTamanho:[{$rTamanho}] são diferentes attrTamanho:[{$atTamanho}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
1721 $result = MigrationRules::_filterVariations(MigrationRules::getPostId(),
1722 ['cor_key'=>'attribute_pa_cor',
1723 'cor_value'=>$pcor,'tamanho_key'=>'attribute_pa_tamanho', 'tamanho_value'=>$rTamanho
1724 ]);
1725
1726 echo "-produtoCor:[{$pcor}|[$rTamanho]] são diferentes AttrCor:[{$acor},{$atTamanho}] (x:{$x}, c:{$c}[Último Produto Local],total(R):{$rtotal},total(L):($totalL), diffP:{$diffProducts}) - variable_id:[$cproducts]|father:$pID | {Cor remota não existe em cores locais} |<br>";
1727
1728 //var_dump($result);
1729 if(empty($result)){
1730 //var_dump($result);
1731 // The variation data
1732 echo "{Cor remota não existe - Cor [{$pcor}] Será persistida} |Tamanho:{$listCorT->produtoTamanho} (x:{$x}, c:{$c},total:{$rtotal}) - variable_id:[$cproducts] | <br>";
1733 $variation_data = [
1734 'attributes' => [
1735 'cor' => $listCorT->produtoCor,
1736 'tamanho' => $listCorT->produtoTamanho,
1737 ],
1738 'sku' => MigrationRules::getProductTeste()->produtoId,
1739 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1740 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1741 'stock_qty' => $_stockRemote
1742 ];
1743 // The function to be run
1744 _create_product_variation(MigrationRules::getPostId(), $variation_data );
1745 //$z++;
1746 }
1747 else{
1748 echo "*produtoCor:[{$pcor}|[$rTamanho]] existe como variacao local na base AttrCor:[{$acor},{$atTamanho}] (x:{$x}, c:{$c},total(R):{$rtotal},total(L):($totalL), diffP:{$diffProducts}) - variable_id:[$cproducts]|father:$pID | {Cor/Tamanho remota existe em cores/tamanhos locais(Operacão: Não atualiza)} |<br>";
1749 //echo "produtoTamanho:[{$rTamanho}] são diferentes attrTamanho:[{$atTamanho}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
1750 $result = MigrationRules::_filterVariations(MigrationRules::getPostId(),
1751 ['cor_key'=>'attribute_pa_cor',
1752 'cor_value'=>$pcor,'tamanho_key'=>'attribute_pa_tamanho', 'tamanho_value'=>$rTamanho
1753 ]);
1754 //var_dump($result[0]->ID);
1755
1756 //if(empty($result)){
1757 //var_dump($result);
1758 // The variation data
1759 echo "{Variaçao de tamanho Existe para a cor:{$pcor} ->{Tamanho:{$listCorT->produtoTamanho}} - Variação de cor:[{$pcor}] Não Será Criada, pois já existe} | (x:{$x}, c:{$c},total:{$rtotal}) - variable_id:[$cproducts] | <br>";
1760 $variation_data = [
1761 'attributes' => [
1762 'cor' => $listCorT->produtoCor,
1763 'tamanho' => $listCorT->produtoTamanho,
1764 ],
1765 'sku' => MigrationRules::getProductTeste()->produtoId,
1766 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1767 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1768 'stock_qty' => $_stockRemote
1769 ];
1770 // The function to be run
1771 //_create_product_variation(MigrationRules::getPostId(), $variation_data );
1772
1773 #
1774 //echo "{Cor remota existe - Cor [{$pcor}] Será Atualizada} |Tamanho:{$listCorT->produtoTamanho} (x:{$x}, c:{$c},total:{$rtotal}) - variable_id:[$cproducts] | <br>";
1775 /*
1776 $variation_data = [
1777 'attributes' => [
1778 'cor' => $listCorT->produtoCor,
1779 'tamanho' => $listCorT->produtoTamanho,
1780 ],
1781 'ID' => $cproducts,
1782 'sku' => MigrationRules::getProductTeste()->produtoId,
1783 'update' => true,
1784 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1785 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1786 'stock_qty' => $_stockRemote
1787 ];
1788 // The function to be run
1789 _create_product_variation(MigrationRules::getPostId(), $variation_data );
1790 */
1791 }
1792
1793
1794 }else{
1795 //echo ">produtoCor:[{$pcor}] são diferentes AttrCor:[{$acor}] ({$x}-{$c}) variable_id:[$cproducts] | <br>";
1796 }
1797
1798 }
1799 //exit;
1800 }
1801
1802 static function setTotalLocalProducts($lproduct){
1803 self::$lproduct = $lproduct;
1804 }
1805
1806 static function setTotalRemoteProducts($rproduct){
1807 self::$rproduct = $rproduct;
1808 }
1809
1810
1811 static function getTotalLocalProducts(){
1812 return self::$lproduct;
1813 }
1814
1815 static function getTotalRemoteProducts(){
1816 return self::$rproduct;
1817 }
1818
1819 static function setCollection($collection){
1820 self::$collection = $collection;
1821 }
1822
1823 static function getCollection(){
1824 return self::$collection;
1825 }
1826
1827
1828 static function setPostId($postId){
1829 self::$postId = $postId;
1830 }
1831
1832 static function getPostId(){
1833 return self::$postId;
1834 }
1835
1836 static function setProdPosition($prodPosition){
1837 self::$prodPosition = $prodPosition;
1838 }
1839
1840 static function getProdPosition(){
1841 return self::$prodPosition;
1842 }
1843
1844 static function setProductTeste($productTeste){
1845 self::$productTeste = $productTeste;
1846 }
1847
1848 static function getProductTeste(){
1849 return self::$productTeste;
1850 }
1851
1852 static function setRemoteAttr($remoteAttr){
1853 self::$remoteAttr = $remoteAttr;
1854 }
1855
1856 static function getRemoteAttr(){
1857 return self::$remoteAttr;
1858 }
1859
1860}
1861
1862class FavelaMigration {
1863
1864 static function listAllVariableProducts($post_id){
1865 //cria uma instancia do produto
1866 $product = wc_get_product($post_id);
1867
1868 //pega todas as variacoes do produto (só os ids)
1869 if(!empty($product)){
1870 $current_products = $product->get_children();
1871 return(count($current_products));
1872 }
1873
1874 }
1875
1876 static function getAllVariableProduct($post_id){
1877 //cria uma instancia do produto
1878 $product = wc_get_product($post_id);
1879 if(!empty($product)){
1880 $current_products = $product->get_children();
1881 return $current_products;
1882 }
1883 }
1884
1885 static function getAllRemoteVariableProduct(stdClass $collection){
1886 return(count($collection->listaCorTamanho));
1887 }
1888
1889 static function getAllRemoteVariableProductNames(stdClass $collection){
1890 foreach($collection->listaCorTamanho as $k=>$coll){
1891 echo "{$coll->produtoCor},{$coll->produtoTamanho} -({$k})<br>";
1892 }
1893 }
1894
1895
1896 static function getAttributesForProduct(stdClass $product){
1897 foreach($product->listaCorTamanho as $p=>$prop){
1898 $cores[] = $prop->produtoCor;
1899 $tamanho[] = $prop->produtoTamanho;
1900 $stock[] = $prop->produtoQtdeEstoque;
1901 }
1902
1903 return array('cores'=>$cores, 'tamanho'=>$tamanho, 'estoque'=>$stock);
1904 }
1905
1906 static function _getAttributesForProduct(stdClass $product){
1907 //echo "<h1>Objeto Remoto como stdClass: </h1>";
1908 //var_dump($product->listaCorTamanho);
1909 //$c = 0;
1910 foreach($product->listaCorTamanho as $p=>$prop){
1911 //$object = $object[$k];
1912 foreach($prop as $k=>$value){
1913 //$attributeMeta[] = $prop->$k;
1914 //$object[] = ["{$k}"=>[$prop->$k]];
1915 //echo "p:[{$p}] k:[{$k}] count:[{$c}] value:[{$value}]<br>";
1916 $attribute = substr($k,7);//produto{AttrName}elimina produto da str
1917 if("QtdeEstoque" != $attribute){
1918 $object[$attribute][] = $product->listaCorTamanho[$p]->$k;
1919 }
1920
1921 }
1922 //echo "<h3>{$product->listaCorTamanho[$p]->$attribute} [{$attribute}]</h3>";
1923 $c++;
1924 }
1925
1926 //var_dump($object);
1927
1928 return $object;
1929 //return array('cores'=>$cores, 'tamanho'=>$tamanho, 'estoque'=>$stock);
1930 }
1931
1932 static function getAllAttributes($post_id){
1933 //exibe os atributos do produto
1934 $prodAttrGlobal = get_post_meta($post_id, '_product_attributes', true );
1935 echo "<h2>Atributos do produto</h2>";
1936 var_dump($prodAttrGlobal);
1937 }
1938
1939 static function getAllAttrForTaxonomy($tax,$post_id){
1940 echo "<h2>termos dos atributos dos produtos(pa_tamanho)</h2>";
1941 $result = woocommerce_get_product_terms($post_id, $tax, 'names');
1942 var_dump($result);
1943 }
1944
1945 static function updateVariableProduct(stdClass $productTeste, array $current_products){
1946 //counters
1947 MigrationRules::setTotalLocalProducts(count($current_products));
1948 MigrationRules::setTotalRemoteProducts(count($productTeste->listaCorTamanho));
1949
1950 $x = 0; $c=0;
1951 //loop (produto remoto / produtos variavies)
1952 foreach($productTeste->listaCorTamanho as $l=>$listCorT){
1953 foreach($current_products as $c=>$cproducts){
1954 $attrCor = get_post_meta($cproducts, 'attribute_pa_cor', true );
1955 //var_dump($attrCor);
1956 $attrTamanho = get_post_meta($cproducts, 'attribute_pa_tamanho', true );
1957 $attrStock = get_post_meta($cproducts, '_stock', true );
1958 //atualiza estoque
1959 MigrationRules::updateStock($listCorT, $attrCor, $attrTamanho, $attrStock, $x, $c, $cproducts);
1960 $x++;//no loop das variacoes locais ($current_products)
1961 }
1962 $c++;//no loop das variacoes remotas ($productTest)
1963 }
1964 }
1965
1966
1967 static function storeVariableProduct(stdClass $productTeste){
1968 //counters
1969 MigrationRules::setTotalRemoteProducts(count($productTeste->listaCorTamanho));
1970 $c=0;
1971 //loop (produto remoto / produtos variavies)
1972 foreach($productTeste->listaCorTamanho as $l=>$listCorT){
1973 MigrationRules::storeStock($listCorT, $c);
1974 $c++;//no loop das variacoes remotas ($productTest)
1975 }
1976 }
1977
1978 static function searchProduct($productTeste){
1979 $result = get_wc_product_by_title($productTeste->produtoNome, $productTeste->produtoMarca);
1980 return $result;
1981 }
1982
1983 static function getAllLocalProducts(){
1984 // Get 10 most recent product IDs in date descending order.
1985 $query = new WC_Product_Query( array(
1986 'limit' => 209,
1987 'orderby' => 'date',
1988 'order' => 'ASC',
1989 ));
1990 $products = $query->get_products();
1991 return $products;
1992 }
1993
1994 static function init($prodPosition){
1995 //recebe uma coleção remota
1996 $collection = getProdutosForWikiWs();
1997 $productTeste = $collection[$prodPosition];
1998 //se colecao for vazia sai do funcao
1999 if(empty($productTeste)){
2000 return;
2001 }
2002
2003 //Busca com base no {titulo}, {nomeDaMarca} na base da loja
2004 //caso exista um produto local com o mesmo nome de um produto remoto.
2005 $resultSearch = self::searchProduct($productTeste);
2006
2007 if(empty($resultSearch)){
2008 echo "<h4>Produto não existe na base Local</h4>";
2009 $pRemotosQNaoExistemLocal[] = $productTeste->produtoNome;
2010 }else{
2011 $totalIds[] = $resultSearch->get_id();
2012 echo "<h4>Produto existe na base Local</h2>";
2013 //var_dump($resultSearch);
2014 }
2015
2016 $pRemotos = self::getAllRemoteVariableProduct($productTeste);
2017 echo "<h2>Total de produtos Variáveis Remotos: <i>[{$pRemotos}]</i></h2>";
2018 //todos os nomes das variáveis remotas
2019 self::getAllRemoteVariableProductNames($productTeste);
2020
2021 //busca os produtos locais baseados no sku = WebService.produtoTest.id
2022 $post_id = wc_get_product_id_by_sku($productTeste->produtoId);
2023
2024 //caso
2025 /*if(!empty($post_id)){
2026 update_post_meta($post_id, '_sku', $productTeste->produtoId, true);
2027 echo "<h2>SKU do produto Manipulado</h2><br>";
2028 var_dump($post_id);
2029 }*/
2030 //var_dump($produtoTeste);
2031 //pega os atributosdo produto remoto (taxonomias e termos)
2032 //$remoteAttributes = self::getAttributesForProduct($productTeste);
2033 $remoteAttributes = self::_getAttributesForProduct($productTeste);
2034 echo "<h1>Array de atributos remotos construido:</h1>";
2035 var_dump($remoteAttributes);
2036
2037 if($post_id != 0){
2038 update_product_variation( array(
2039 'ID' => $post_id,
2040 'author' => '', // optional
2041 'title' => "{$productTeste->produtoNome}, {$productTeste->produtoMarca}",
2042 'content' => "{$productTeste->produtoNome} - {$productTeste->produtoDescricao} - {$productTeste->produtoMarca} - {$productTeste->produtoCaracteristicas}" ,
2043 'excerpt' => $productTeste->produtoDescricao,
2044 'regular_price' => $productTeste->produtoPrecoBase, // product regular price
2045 'sale_price' => $productTeste->produtoPrecoPromo, // product sale price (optional)
2046 'stock' => $collection[$prodPosition]->listaCorTamanho[0]->produtoQtdeEstoque,
2047 'manager_stock' => '0',
2048 'category' => $productTeste->produtoCat,
2049 // Set a minimal stock quantity
2050 'image_id' => '', // optional
2051 'gallery_ids' => array(), // optional
2052 'sku' => $productTeste->produtoId, // optional
2053 'tax_class' => '', // optional
2054 'weight' => $productTeste->produtoPeso, // optional
2055 'width' => $productTeste->produtoDimensaoL,
2056 'length' => $productTeste->produtoDimensaoC,
2057 // For NEW attributes/values use NAMES (not slugs)
2058 'attributes' => $remoteAttributes,
2059 ));
2060 }else{
2061 //var_dump($produtoTeste);
2062 $post_id = update_product_variation( array(
2063 'author' => '', // optional
2064 'title' => "{$productTeste->produtoNome}, {$productTeste->produtoMarca}",
2065 'content' => "{$productTeste->produtoNome} - {$productTeste->produtoDescricao} - {$productTeste->produtoMarca} - {$productTeste->produtoCaracteristicas}" ,
2066 'excerpt' => $productTeste->produtoDescricao,
2067 'category' => $productTeste->produtoCat,
2068 'regular_price' => $productTeste->produtoPrecoBase, // product regular price
2069 'sale_price' => $productTeste->produtoPrecoPromo, // product sale price (optional)
2070 'stock' => $collection[$prodPosition]->listaCorTamanho[0]->produtoQtdeEstoque,
2071 'manager_stock' => '0',
2072 // Set a minimal stock quantity
2073 'image_id' => '', // optional
2074 'gallery_ids' => array(), // optional
2075 'sku' => $productTeste->produtoId, // optional
2076 'tax_class' => '', // optional
2077 'weight' => $productTeste->produtoPeso, // optional
2078 'width' => $productTeste->produtoDimensaoL,
2079 'length' => $productTeste->produtoDimensaoC,
2080 // For NEW attributes/values use NAMES (not slugs)
2081 'attributes' => $remoteAttributes,
2082 ) );
2083 }
2084 //exit;
2085
2086 //lista todos os produtos variáveis.
2087 echo "<h1>Total de Variações Locais</h1>";
2088 var_dump(self::listAllVariableProducts($post_id));
2089
2090 //exibe todos os attributos
2091 self::getAllAttributes($post_id);
2092
2093 //exibe todos os termos (por taxonomia)
2094 self::getAllAttrForTaxonomy($tax='pa_cor',$post_id);
2095
2096 //retorna um array contendo todos os ids de produtos variáveis
2097 $current_products = self::getAllVariableProduct($post_id);
2098 //atualiza a loja com base nas informacoes dos produtos variaveis do WS
2099 MigrationRules::setCollection($collection);
2100 MigrationRules::setPostId($post_id);
2101 MigrationRules::setProdPosition($prodPosition);
2102 MigrationRules::setProductTeste($productTeste);
2103 MigrationRules::setRemoteAttr($remoteAttributes);
2104
2105 //post_id, $collection, prodposition, productTeste, remoteAttr
2106 if(empty($current_products)){
2107 self::storeVariableProduct($productTeste);
2108 }
2109 else{
2110 self::updateVariableProduct($productTeste,$current_products);
2111 }
2112
2113
2114 }
2115}
2116
2117function createTerms($post_id, $attributes_data){
2118 if( sizeof($attributes_data) > 0 ){
2119 $attributes = array(); // Initializing
2120
2121 // Loop through defined attribute data
2122 foreach( $attributes_data as $key => $attribute_array ) {
2123 if( isset($attribute_array['name']) && isset($attribute_array['options']) ){
2124 // Clean attribute name to get the taxonomy
2125 $taxonomy = 'pa_' . wc_sanitize_taxonomy_name( $attribute_array['name'] );
2126
2127 $option_term_ids = array(); // Initializing
2128
2129 // Loop through defined attribute data options (terms values)
2130 foreach( $attribute_array['options'] as $option ){
2131 if( term_exists( $option, $taxonomy ) ){
2132 // Save the possible option value for the attribute which will be used for variation later
2133 wp_set_object_terms($post_id, $option, $taxonomy, true );
2134 // Get the term ID
2135 $option_term_ids[] = get_term_by( 'name', $option, $taxonomy )->term_id;
2136 }else{
2137 //wp_set_object_terms($post_id, $option, $taxonomy, true );
2138 //$option_term_ids[] = get_term_by( 'name', $option, $taxonomy )->term_id;
2139 //var_dump($option_term_ids);
2140 }
2141 }
2142 }
2143
2144 // Loop through defined attribute data
2145 $attributes[$taxonomy] = array(
2146 'name' => $taxonomy,
2147 'value' => $option_term_ids, // Need to be term IDs
2148 'position' => $key + 1,
2149 'is_visible' => $attribute_array['visible'],
2150 'is_variation' => $attribute_array['variation'],
2151 'is_taxonomy' => '1'
2152 );
2153 }
2154 // Save the meta entry for product attributes
2155 update_post_meta( $post_id, '_product_attributes', $attributes);
2156
2157 }
2158}
2159
2160function create_product_attribute( $label_name ){
2161 global $wpdb;
2162
2163 $slug = sanitize_title( $label_name );
2164
2165 if ( strlen( $slug ) >= 28 ) {
2166 return new WP_Error( 'invalid_product_attribute_slug_too_long', sprintf( __( 'Name "%s" is too long (28 characters max). Shorten it, please.', 'woocommerce' ), $slug ), array( 'status' => 400 ) );
2167 } elseif ( wc_check_if_attribute_name_is_reserved( $slug ) ) {
2168 return new WP_Error( 'invalid_product_attribute_slug_reserved_name', sprintf( __( 'Name "%s" is not allowed because it is a reserved term. Change it, please.', 'woocommerce' ), $slug ), array( 'status' => 400 ) );
2169 } elseif ( taxonomy_exists( wc_attribute_taxonomy_name( $label_name ) ) ) {
2170 return new WP_Error( 'invalid_product_attribute_slug_already_exists', sprintf( __( 'Name "%s" is already in use. Change it, please.', 'woocommerce' ), $label_name ), array( 'status' => 400 ) );
2171 }
2172
2173 $data = array(
2174 'attribute_label' => $label_name,
2175 'attribute_name' => $slug,
2176 'attribute_type' => 'select',
2177 'attribute_orderby' => 'menu_order',
2178 'attribute_public' => 0, // Enable archives ==> true (or 1)
2179 );
2180
2181 $results = $wpdb->insert( "{$wpdb->prefix}woocommerce_attribute_taxonomies", $data );
2182
2183 if ( is_wp_error( $results ) ) {
2184 return new WP_Error( 'cannot_create_attribute', $results->get_error_message(), array( 'status' => 400 ) );
2185 }
2186
2187 $id = $wpdb->insert_id;
2188
2189 do_action('woocommerce_attribute_added', $id, $data);
2190
2191 wp_schedule_single_event( time(), 'woocommerce_flush_rewrite_rules' );
2192
2193 delete_transient('wc_attribute_taxonomies');
2194}
2195
2196/**
2197 * Save a new product attribute from his name (slug).
2198 *
2199 * @since 3.0.0
2200 * @param string $name | The product attribute name (slug).
2201 * @param string $label | The product attribute label (name).
2202 */
2203function save_product_attribute_from_name( $name, $label='', $set=true ){
2204 if( ! function_exists ('get_attribute_id_from_name') ) return;
2205
2206 global $wpdb;
2207
2208 $label = $label == '' ? ucfirst($name) : $label;
2209 $attribute_id = get_attribute_id_from_name( $name );
2210
2211 if( empty($attribute_id) ){
2212 $attribute_id = NULL;
2213 } else {
2214 $set = false;
2215 }
2216 $args = array(
2217 'attribute_id' => $attribute_id,
2218 'attribute_name' => $name,
2219 'attribute_label' => $label,
2220 'attribute_type' => 'select',
2221 'attribute_orderby' => 'menu_order',
2222 'attribute_public' => 0,
2223 );
2224
2225 if( empty($attribute_id) ) {
2226 $wpdb->insert( "{$wpdb->prefix}woocommerce_attribute_taxonomies", $args );
2227 set_transient( 'wc_attribute_taxonomies', false );
2228 }
2229
2230 if( $set ){
2231 $attributes = wc_get_attribute_taxonomies();
2232 $args['attribute_id'] = get_attribute_id_from_name( $name );
2233 $attributes[] = (object) $args;
2234 //print_r($attributes);
2235 set_transient( 'wc_attribute_taxonomies', $attributes );
2236 } else {
2237 return;
2238 }
2239}
2240
2241/**
2242 * Get the product attribute ID from the name.
2243 *
2244 * @since 3.0.0
2245 * @param string $name | The name (slug).
2246 */
2247function get_attribute_id_from_name( $name ){
2248 global $wpdb;
2249 $attribute_id = $wpdb->get_col("SELECT attribute_id
2250 FROM {$wpdb->prefix}woocommerce_attribute_taxonomies
2251 WHERE attribute_name LIKE '$name'");
2252 return reset($attribute_id);
2253}
2254
2255/**
2256 * Create a new variable product (with new attributes if they are).
2257 * (Needed functions:
2258 *
2259 * @since 3.0.0
2260 * @param array $data | The data to insert in the product.
2261 */
2262
2263function create_product_variation( $data ){
2264 if( ! function_exists ('save_product_attribute_from_name') ) return;
2265
2266 $postname = sanitize_title( $data['title'] );
2267 $author = empty( $data['author'] ) ? '1' : $data['author'];
2268
2269 $post_data = array(
2270 'post_author' => $author,
2271 'post_name' => $postname,
2272 'post_title' => $data['title'],
2273 'post_content' => $data['content'],
2274 'post_excerpt' => $data['excerpt'],
2275 'post_status' => 'publish',
2276 'ping_status' => 'closed',
2277 'post_type' => 'product_variation',
2278 'post_parent' => $data['parent_id'],
2279 'guid' => home_url( '/product/'.$postname.'/' ),
2280 );
2281
2282 // Creating the product (post data)
2283 //$product_id = wp_insert_post( );
2284 $result = wp_insert_post( $post_data );
2285
2286 if ( $result && ! is_wp_error( $result ) ) {
2287 $product_id = $result;
2288 // Do something else
2289 var_dump($result);
2290 echo "sucesso";
2291 }else{
2292 echo "erro ao gravar produto variavel";
2293 var_dump($result);
2294 }
2295 // Get an instance of the WC_Product_Variable object and save it
2296 $product = new WC_Product_Variation( $product_id );
2297
2298 ## ---------------------- Other optional data ---------------------- ##
2299 ## (see WC_Product and WC_Product_Variable setters methods)
2300
2301 // THE PRICES (No prices yet as we need to create product variations)
2302
2303 // IMAGES GALLERY
2304 // Prices
2305 if( empty( $data['sale_price'] ) ){
2306 $product->set_price( $data['regular_price'] );
2307 } else {
2308 $product->set_price($data['sale_price'] );
2309 $product->set_sale_price($data['sale_price'] );
2310 }
2311 $variation->set_regular_price($data['regular_price'] );
2312
2313 if( ! empty( $data['gallery_ids'] ) && count( $data['gallery_ids'] ) > 0 )
2314 $product->set_gallery_image_ids( $data['gallery_ids'] );
2315
2316 // SKU/*
2317// if( ! empty( $data['sku'] ) )
2318 // $product->set_sku( $data['sku'] );
2319
2320
2321 // STOCK (stock will be managed in variations)
2322 $product->set_stock_quantity($data['stock']); // Set a minimal stock quantity
2323 if($data['manager_stock'] == '0'){
2324 $product->set_manage_stock(false);
2325 }else{
2326 $product->set_manage_stock(true);
2327 }
2328
2329 $product->set_stock_status('');
2330
2331 // Tax class
2332 if( empty( $data['tax_class'] ) )
2333 $product->set_tax_class( $data['tax_class'] );
2334
2335 // WEIGHT
2336 if( ! empty($data['weight']) )
2337 $product->set_weight(''); // weight (reseting)
2338 else
2339 $product->set_weight($data['weight']);
2340
2341 $product->validate_props(); // Check validation
2342
2343 ## ---------------------- VARIATION ATTRIBUTES ---------------------- ##
2344
2345 $product_attributes = array();
2346
2347 foreach( $data['attributes'] as $key => $terms ){
2348 $taxonomy = wc_attribute_taxonomy_name($key); // The taxonomy slug
2349 $attr_label = ucfirst($key); // attribute label name
2350 $attr_name = ( wc_sanitize_taxonomy_name($key)); // attribute slug
2351
2352 // NEW Attributes: Register and save them
2353 if( ! taxonomy_exists( $taxonomy ) )
2354 save_product_attribute_from_name( $attr_name, $attr_label );
2355
2356 $product_attributes[$taxonomy] = array (
2357 'name' => $taxonomy,
2358 'value' => '',
2359 'position' => '',
2360 'is_visible' => 0,
2361 'is_variation' => 1,
2362 'is_taxonomy' => 1
2363 );
2364
2365 foreach( $terms as $value ){
2366 $term_name = ucfirst($value);
2367 $term_slug = sanitize_title($value);
2368
2369 // Check if the Term name exist and if not we create it.
2370 if( ! term_exists( $value, $taxonomy ) )
2371 wp_insert_term( $term_name, $taxonomy, array('slug' => $term_slug ) ); // Create the term
2372
2373 // Set attribute values
2374 wp_set_post_terms( $product_id, $term_name, $taxonomy, true );
2375 }
2376 }
2377 update_post_meta( $product_id, '_product_attributes', $product_attributes );
2378
2379 $product->save(); // Save the data
2380}
2381
2382function get_product_category($catname){
2383 if($catname == ''){
2384 $catname = "CAMISAS";
2385 }else{
2386 $catnamesub = $catname;
2387 $slug = $catnamesub;
2388 //var_dump($slug);
2389 $productCategory = get_term_by( 'name', $slug, 'product_cat' );
2390
2391 //echo "termo Id";
2392 //var_dump($productCategory->term_id);
2393 if($productCategory){
2394 $cat_id = get_term_by('id',$productCategory->term_id , 'product_cat' );
2395 }else{
2396 return false;
2397 }
2398 //$cat_id = get_category($productCategory->term_id);
2399 //echo "cat_id";
2400 //var_dump($cat_id);
2401 }
2402
2403 if(empty($cat_id)) {
2404 //echo "insere um termo se não existir a categoria<br>";
2405 //var_dump($cat_id);
2406 $arg = array( 'description' => $slug, 'parent' => 0 );
2407 $cat_id = wp_insert_term($slug, "product_cat", $arg);
2408 //echo "id inserido da categoria criada<br>";
2409 //var_dump($cat_id);
2410 return $cat_id['term_id'];
2411 }else{
2412 //var_dump("retornando resultado existindo uma categoria correspondente");
2413 return $cat_id->term_id;
2414 }
2415}
2416/**
2417 * Update a new variable product (with new attributes if they are).
2418 * (Needed functions:
2419 *
2420 * @since 3.0.0
2421 * @param array $data | The data to insert in the product.
2422 */
2423function update_product_variation($data){
2424 if( ! function_exists ('save_product_attribute_from_name') ) return;
2425
2426 $category_id = get_product_category($data['category']);
2427 $postname = sanitize_title( $data['title'] );
2428 $author = empty( $data['author'] ) ? '1' : $data['author'];
2429
2430 if(empty($data['excerpt'])){
2431 $data['excerpt'] = $postname;
2432 }
2433
2434
2435 if(empty($data['ID'])){
2436
2437 $post_data = array(
2438 'post_author' => $author,
2439 'post_name' => $postname,
2440 'post_title' => $data['title'],
2441 'post_content' => $data['content'],
2442 'post_excerpt' => $data['excerpt'],
2443 'post_status' => 'publish',
2444 'ping_status' => 'closed',
2445 'post_type' => 'product',
2446 'guid' => home_url( '/product/'.$postname.'/') ,
2447 'tax_input' => ['product_cat' => $category_id]
2448 );
2449
2450 $product_id = wp_insert_post( $post_data );
2451 //wp_set_post_terms($product_id, get_term()->slug,'product_cat',true);
2452 }else{
2453
2454 if(!$data['insert_variable_product_unique']){
2455 $post_data = array(
2456 'ID' => $data['ID'],
2457 'post_author' => $author,
2458 'post_name' => $postname,
2459 'post_title' => $data['title'],
2460 'post_content' => $data['content'],
2461 'post_excerpt' => $data['excerpt'],
2462 'post_status' => 'publish',
2463 'ping_status' => 'closed',
2464 'post_type' => 'product',
2465 'guid' => home_url( '/product/'.$postname.'/' ),
2466 'tax_input' => ['product_cat'=>$category_id]
2467 );
2468 $product_id = wp_update_post( $post_data );
2469 }
2470
2471 }
2472
2473 $product = new WC_Product_Variable( $product_id );
2474 $product->save();
2475
2476 ## ---------------------- Other optional data ---------------------- ##
2477 ## (see WC_Product and WC_Product_Variable setters methods)
2478
2479 //THE PRICES (No prices yet as we need to create product variations)
2480 //IMAGES GALLERY
2481 if( ! empty( $data['gallery_ids'] ) && count( $data['gallery_ids'] ) > 0 )
2482 $product->set_gallery_image_ids( $data['gallery_ids'] );
2483
2484 //SKU
2485 if( ! empty( $data['sku'] ) )
2486 $product->set_sku( $data['sku'] );
2487
2488 // STOCK (stock will be managed in variations)
2489 $product->set_stock_quantity( $data['stock'] ); // Set a minimal stock quantity
2490 if($data['manager_stock'] == '0'){
2491 $product->set_manage_stock(false);
2492 }else{
2493 $product->set_manage_stock(true);
2494 }
2495
2496 $product->set_stock_status('');
2497
2498 // Tax class
2499 if( empty( $data['tax_class'] ) )
2500 $product->set_tax_class( $data['tax_class'] );
2501
2502 // WEIGHT
2503 if( ! empty($data['weight']) )
2504 $product->set_weight(''); // weight (reseting)
2505 else
2506 $product->set_weight($data['weight']);
2507
2508 //length
2509 if( ! empty($data['length']) )
2510 $product->set_length(''); // length (reseting)
2511 else
2512 $product->set_length($data['length']);
2513
2514 $product->validate_props(); // Check validation
2515
2516 //WIDTH
2517 if( ! empty($data['width']) )
2518 $product->set_width(""); // weight (reseting)
2519else
2520 $product->set_width($data['width']);
2521
2522 ## ---------------------- VARIATION ATTRIBUTES ---------------------- ##
2523
2524 $product_attributes = array();
2525 //var_dump($product);
2526 var_dump($data['attributes']);
2527 foreach( $data['attributes'] as $key => $terms ){
2528 $taxonomy = wc_attribute_taxonomy_name($key); // The taxonomy slug
2529 $attr_label = ucfirst($key); // attribute label name
2530 $attr_name = ( wc_sanitize_taxonomy_name($key)); // attribute slug
2531
2532 // NEW Attributes: Register and save them
2533 if( ! taxonomy_exists( $taxonomy ) )
2534 save_product_attribute_from_name( $attr_name, $attr_label );
2535
2536 $product_attributes[$taxonomy] = array (
2537 'name' => $taxonomy,
2538 'value' => '',
2539 'position' => '',
2540 'is_visible' => 0,
2541 'is_variation' => 1,
2542 'is_taxonomy' => 1
2543 );
2544
2545 foreach( $terms as $value ){
2546 $term_name = ucfirst($value);
2547 $term_slug = sanitize_title($value);
2548
2549 // Check if the Term name exist and if not we create it.
2550 if( ! term_exists( $value, $taxonomy ) )
2551 wp_insert_term( $term_name, $taxonomy, array('slug' => $term_slug ) ); // Create the term
2552
2553 // Set attribute values
2554 if($data['insert_variable_product_unique']){
2555 wp_set_post_terms( $data['ID'], $term_name, $taxonomy, true );
2556 }else{
2557 wp_set_post_terms( $product_id, $term_name, $taxonomy, true );
2558 }
2559
2560 }
2561 }
2562 //print_r($product);
2563 if(isset($data['insert_variable_product_unique'])){
2564 update_post_meta( $data['ID'], '_product_attributes', $product_attributes );
2565 }else{
2566 update_post_meta( $product_id, '_product_attributes', $product_attributes );
2567 }
2568 //var_dump($product);
2569 //exit;
2570 $product->save(); // Save the data
2571 return $product_id;
2572}
2573/*
2574*
2575$parent_id = 746; // Or get the variable product id dynamically
2576
2577// The variation data
2578$variation_data = array(
2579 'attributes' => array(
2580 'size' => 'M',
2581 'color' => 'Green',
2582 ),
2583 'sku' => '',
2584 'regular_price' => '22.00',
2585 'sale_price' => '',
2586 'stock_qty' => 10,
2587);
2588
2589// The function to be run
2590create_product_variation( $parent_id, $variation_data );
2591*/
2592/**
2593 * Create a product variation for a defined variable product ID.
2594 *
2595 * @since 3.0.0
2596 * @param int $product_id | Post ID of the product parent variable product.
2597 * @param array $variation_data | The data to insert in the product.
2598 */
2599
2600function _create_product_variation( $product_id, $variation_data ){
2601 // Get the Variable product object (parent)
2602 $product = wc_get_product($product_id);
2603
2604 // Creating the product variation
2605 if(empty($variation_data['update'])){
2606 //var_dump($variation_data);
2607 $variation_post = array(
2608 'post_title' => MigrationRules::getProductTeste()->produtoNome,
2609 'post_name' => 'product-'. MigrationRules::getPostId() .'-variation',
2610 'post_status' => 'publish',
2611 'post_parent' => MigrationRules::getPostId(),
2612 'post_type' => 'product_variation',
2613 'guid' => site_url() . "/" . MigrationRules::getPostId()
2614 );
2615
2616 $variation_id = wp_insert_post( $variation_post );
2617 }else{
2618
2619 $variation_post = array(
2620 'ID' => $variation_data['ID'],
2621 'post_title' => $product->get_name(),
2622 'post_name' => 'product-'.$product_id.'-variation',
2623 'post_status' => 'publish',
2624 'post_parent' => $product_id,
2625 'post_type' => 'product_variation',
2626 'guid' => $product->get_permalink()
2627 );
2628
2629 $variation_id = wp_update_post( $variation_post );
2630 }
2631
2632
2633
2634 // Get an instance of the WC_Product_Variation object
2635 $variation = new WC_Product_Variation( $variation_id );
2636 //var_dump($variation_id);
2637 //exit;
2638
2639 foreach ($variation_data['attributes'] as $attribute => $term_name )
2640 {
2641 $taxonomy = 'pa_'.$attribute; // The attribute taxonomy
2642
2643 // If taxonomy doesn't exists we create it (Thanks to Carl F. Corneil)
2644 if( ! taxonomy_exists( $taxonomy ) ){
2645 register_taxonomy(
2646 $taxonomy,
2647 'product_variation',
2648 array(
2649 'hierarchical' => false,
2650 'label' => ucfirst( $attribute ),
2651 'query_var' => true,
2652 'rewrite' => array( 'slug' => sanitize_title($attribute) ), // The base slug
2653 )
2654 );
2655 }
2656
2657 // Check if the Term name exist and if not we create it.
2658 if( ! term_exists( $term_name, $taxonomy ) )
2659 wp_insert_term( $term_name, $taxonomy ); // Create the term
2660
2661 $term_slug = get_term_by('name', $term_name, $taxonomy )->slug; // Get the term slug
2662
2663 // Get the post Terms names from the parent variable product.
2664 $post_term_names = wp_get_post_terms( $product_id, $taxonomy, array('fields' => 'names') );
2665
2666 // Check if the post term exist and if not we set it in the parent variable product.
2667 if( ! in_array( $term_name, $post_term_names ) )
2668 wp_set_post_terms( $product_id, $term_name, $taxonomy, true );
2669
2670 // Set/save the attribute data in the product variation
2671 update_post_meta( $variation_id, 'attribute_'.$taxonomy, $term_slug, true);
2672 }
2673
2674 ## Set/save all other data
2675
2676
2677 // SKU
2678 //if( ! empty( $variation_data['sku'] ) )
2679 // $variation->set_sku( $variation_data['sku'] );
2680
2681 // Prices
2682 if( empty( $variation_data['sale_price'] ) ){
2683 $variation->set_price( $variation_data['regular_price'] );
2684 } else {
2685 $variation->set_price( $variation_data['sale_price'] );
2686 $variation->set_sale_price( $variation_data['sale_price'] );
2687 }
2688 $variation->set_regular_price( $variation_data['regular_price'] );
2689
2690 // Stock
2691 var_dump($variation_data['stock_qty']);
2692 if( ! empty($variation_data['stock_qty']) ){
2693 $variation->set_stock_quantity( $variation_data['stock_qty'] );
2694 $variation->set_manage_stock(true);
2695 $variation->set_stock_status('');
2696 } else {
2697 $variation->set_manage_stock(true);
2698 }
2699
2700 $variation->set_weight(''); // weight (reseting)
2701 //var_dump( $variation_data['ID']);
2702 $variation->save(); // Save the data
2703 //var_dump($variation->get_stock_quantity());
2704 //exit;
2705}
2706
2707function tirarAcentos($string){
2708 return preg_replace(array("/(á|à|ã|â|ä)/","/(Á|À|Ã|Â|Ä)/","/(é|è|ê|ë)/","/(É|È|Ê|Ë)/","/(í|ì|î|ï)/","/(Í|Ì|Î|Ï)/","/(ó|ò|õ|ô|ö)/","/(Ó|Ò|Õ|Ô|Ö)/","/(ú|ù|û|ü)/","/(Ú|Ù|Û|Ü)/","/(ñ)/","/(Ñ)/"),explode(" ","a A e E i I o O u U n N"),$string);
2709}
2710
2711/**
2712 * Method to delete Woo Product
2713 *
2714 * @param int $id the product ID.
2715 * @param bool $force true to permanently delete product, false to move to trash.
2716 * @return \WP_Error|boolean
2717 */
2718function wh_deleteProduct($id, $force = FALSE)
2719{
2720 $product = wc_get_product($id);
2721
2722 if(empty($product))
2723 return new WP_Error(999, sprintf(__('No %s is associated with #%d', 'woocommerce'), 'product', $id));
2724
2725 // If we're forcing, then delete permanently.
2726 if ($force)
2727 {
2728 if ($product->is_type('variable'))
2729 {
2730 foreach ($product->get_children() as $child_id)
2731 {
2732 $child = wc_get_product($child_id);
2733 $child->delete(true);
2734 }
2735 }
2736 elseif ($product->is_type('grouped'))
2737 {
2738 foreach ($product->get_children() as $child_id)
2739 {
2740 $child = wc_get_product($child_id);
2741 $child->set_parent_id(0);
2742 $child->save();
2743 }
2744 }
2745
2746 $product->delete(true);
2747 $result = $product->get_id() > 0 ? false : true;
2748 }
2749 else
2750 {
2751 $product->delete();
2752 $result = 'trash' === $product->get_status();
2753 }
2754
2755 if (!$result)
2756 {
2757 return new WP_Error(999, sprintf(__('This %s cannot be deleted', 'woocommerce'), 'product'));
2758 }
2759
2760 // Delete parent product transients.
2761 if ($parent_id = wp_get_post_parent_id($id))
2762 {
2763 wc_delete_product_transients($parent_id);
2764 }
2765 return true;
2766}
2767
2768/**
2769 * Add a widget to the dashboard.
2770 *
2771 * This function is hooked into the 'wp_dashboard_setup' action below.
2772 */
2773function wporg_add_dashboard_widgets() {
2774 wp_add_dashboard_widget(
2775 'wporg_dashboard_widget', // Widget slug.
2776 esc_html__( 'Wiki Importer', 'wporg' ), // Title.
2777 'wporg_dashboard_widget_render' // Display function.
2778 );
2779}
2780add_action( 'wp_dashboard_setup', 'wporg_add_dashboard_widgets' );
2781
2782/**
2783 * Create the function to output the content of our Dashboard Widget.
2784 */
2785function wporg_dashboard_widget_render() {
2786 // Display whatever you want to show.
2787 $html = '<h2>Clique <a href="admin.php?action=executeWikiImport">aqui</a> para importar Dados do ERP Wiki</h2>
2788 <img src="https://img2.pngio.com/data-import-microbiz-cloud-pos-import-data-png-537_368.png"/>';
2789 echo $html;
2790}
2791
2792add_action( 'importInitializer', 'executeWikiImport', 20,0);
2793do_action('importInitializer');
2794
2795function executeWikiImport(){
2796 if(isset($_GET['action']) && $_GET['action']=="executeWikiImport"){
2797 //initMigration();
2798 //initMigration();
2799 //create curl resource
2800 $ch = curl_init();
2801 curl_setopt($ch, CURLOPT_URL, "http://localhost/favelachick/checkout/order-received/19606/?key=wc_order_1TMRfz22JXnYf");
2802 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
2803 $output = curl_exec($ch);
2804 curl_close($ch);
2805 }
2806}
2807
2808