· 4 years ago · Mar 04, 2021, 04:14 AM
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
847add_filter( 'woocommerce_rest_check_permissions', 'my_woocommerce_rest_check_permissions', 90, 4 );
848function my_woocommerce_rest_check_permissions( $permission, $context, $object_id, $post_type ){
849 return true;
850}
851
852
853function get_wc_product_by_title( $title, $post_marca){
854 global $wpdb;
855 global $postTitle;
856
857 $post_title = urldecode(strval($title));
858 $post_marca = urldecode(strval($post_marca));
859 $postTitle[] = $post_title;
860
861 $title_name_marca = $post_title . ", ". $post_marca;
862
863 //echo "IMPRIMINDO OS TÍTULOS PASSADOS PELO WS";
864 //var_dump($postTitle);
865
866 $post_table = $wpdb->prefix . "posts";
867 $result = $wpdb->get_col(
868 "SELECT
869 posts.ID, posts.post_title
870 FROM wp_posts AS posts INNER JOIN wp_term_relationships AS term_relationships
871 ON posts.ID = term_relationships.object_id INNER JOIN wp_term_taxonomy AS term_taxonomy
872 ON term_relationships.term_taxonomy_id = term_taxonomy.term_taxonomy_id
873 INNER JOIN wp_terms AS terms
874 ON term_taxonomy.term_id = terms.term_id
875 WHERE term_taxonomy.taxonomy = 'product_type'
876 AND posts.post_title LIKE '%$title_name_marca%'
877 AND posts.post_type = 'product'"
878 );
879
880 //var_dump($post_title);
881 //var_dump($result);
882 // We exit if title doesn't match
883 $result2 = $wpdb->get_col(
884 "SELECT
885 posts.ID, posts.post_title
886 FROM wp_posts AS posts INNER JOIN wp_term_relationships AS term_relationships
887 ON posts.ID = term_relationships.object_id INNER JOIN wp_term_taxonomy AS term_taxonomy
888 ON term_relationships.term_taxonomy_id = term_taxonomy.term_taxonomy_id
889 INNER JOIN wp_terms AS terms
890 ON term_taxonomy.term_id = terms.term_id
891 WHERE term_taxonomy.taxonomy = 'product_type'
892 AND posts.post_status NOT IN('trash')
893 AND posts.post_title LIKE '%$title_name_marca%'
894 AND posts.post_type = 'product'"
895 );
896
897 if(empty($result2[0])){
898 return;
899 }
900 else{
901
902 //var_dump($result2[0]);
903 }
904
905 if( empty( $result[0] ) )
906 return;
907 else
908 //print_r(wc_get_product( intval( $result[0])));
909 return wc_get_product( $result2[0] );
910}
911
912
913
914function getProdutosForWikiWs(){
915
916 $ch = curl_init();
917 curl_setopt_array($ch, array(
918 //CURLOPT_URL => "http://app.wikisistemas.com.br:8086/ecommerceexternowebservice.asmx/getProdutosAtivosEcommerceComEstoque?empresa=392&guid=4c6e6dab-6d6d-43d9-8f71-7f12158f8f85&estoquePositivo=0",
919 CURLOPT_URL => "http://app.wikisistemas.com.br:8086/ecommerceexternowebservice.asmx/getProdutosAtivosEcommerceComEstoque?empresa=460&guid=9351c4b5-8c8a-4657-8244-56cb46e5e5d8&estoquePositivo=0",
920 CURLOPT_RETURNTRANSFER => true,
921 CURLOPT_ENCODING => "",
922 CURLOPT_MAXREDIRS => 10,
923 CURLOPT_TIMEOUT => 30,
924 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
925 CURLOPT_CUSTOMREQUEST => "GET",
926 CURLOPT_SSL_VERIFYPEER=> false,
927
928 CURLOPT_HTTPHEADER => array(
929 "Authorization: Basic *****************",
930 "Cache-Control: no-cache"
931 ),
932 ));
933
934 //$result = curl_exec($ch);
935
936 $collection = json_decode(_getJson());
937 //$collection = json_decode($result);
938 return $collection;
939
940 //curl_close($ch);
941 }
942
943/*
944//usage
945$parent_id = 746; // Or get the variable product id dynamically
946
947//The variation data
948$variation_data = array(
949 'attributes' => array(
950 'size' => 'M',
951 'color' => 'Green',
952 ),
953 'sku' => '',
954 'regular_price' => '22.00',
955 'sale_price' => '',
956 'stock_qty' => 10,
957);
958
959// The function to be run
960create_product_variation( $parent_id, $variation_data );
961*/
962
963function insertSimpleProduct(){
964 $post = array(
965 'post_author' => $user_id,
966 'post_content' => '',
967 'post_status' => "publish",
968 'post_title' => $product->part_num,
969 'post_parent' => '',
970 'post_type' => "product",
971 );
972
973 //Create post
974 $post_id = wp_insert_post( $post, $wp_error );
975 if($post_id){
976 $attach_id = get_post_meta($product->parent_id, "_thumbnail_id", true);
977 add_post_meta($post_id, '_thumbnail_id', $attach_id);
978 }
979
980 wp_set_object_terms( $post_id, 'Races', 'product_cat' );
981 wp_set_object_terms( $post_id, 'simple', 'product_type');
982
983 update_post_meta( $post_id, '_visibility', 'visible' );
984 update_post_meta( $post_id, '_stock_status', 'instock');
985 update_post_meta( $post_id, 'total_sales', '0');
986 update_post_meta( $post_id, '_downloadable', 'yes');
987 update_post_meta( $post_id, '_virtual', 'yes');
988 update_post_meta( $post_id, '_regular_price', "1" );
989 update_post_meta( $post_id, '_sale_price', "1" );
990 update_post_meta( $post_id, '_purchase_note', "" );
991 update_post_meta( $post_id, '_featured', "no" );
992 update_post_meta( $post_id, '_weight', "" );
993 update_post_meta( $post_id, '_length', "" );
994 update_post_meta( $post_id, '_width', "" );
995 update_post_meta( $post_id, '_height', "" );
996 update_post_meta( $post_id, '_sku', "");
997 update_post_meta( $post_id, '_product_attributes', array());
998 update_post_meta( $post_id, '_sale_price_dates_from', "" );
999 update_post_meta( $post_id, '_sale_price_dates_to', "" );
1000 update_post_meta( $post_id, '_price', "1" );
1001 update_post_meta( $post_id, '_sold_individually', "" );
1002 update_post_meta( $post_id, '_manage_stock', "no" );
1003 update_post_meta( $post_id, '_backorders', "no" );
1004 update_post_meta( $post_id, '_stock', "" );
1005}
1006
1007add_action( 'woocommerce_thankyou', 'initMigration', 20, 2 );
1008
1009function initMigration(){
1010 /*
1011 for($i=0;$i<=186;$i++){
1012 //FavelaMigration::init($prodPosition=185);
1013 echo "no loop: {$i}";
1014 FavelaMigration::init($i);
1015 }
1016 return;*/
1017 //pega todos os dados do WS
1018 $collection = getProdutosForWikiWs();
1019 //cria um array de nomes remotos
1020
1021 $totalRemoteP = count($collection);
1022
1023 for($i=0;$i <= count($collection);$i++){
1024 //FavelaMigration::init($prodPosition=185);
1025 echo "no loop: {$i} [{$totalRemoteP}]";
1026 FavelaMigration::init($i);
1027 }
1028
1029
1030 $remoteName = [];
1031 foreach($collection as $cln=>$coll){
1032 $remoteName[] = "{$coll->produtoNome}, {$coll->produtoMarca}";
1033 }
1034
1035 #inicializa variáveis de operacao
1036 //variaveis locais
1037 $localProducts = FavelaMigration::getAllLocalProducts();
1038 //var_dump($localProducts);
1039 $notExistsProduct = [];
1040 //total de ids (local/remoto)
1041 $totalIds = [];
1042 $idsQDiferetem = [];
1043 $idsQBatem = [];
1044 $totalNames = [];
1045 $remoteSlug = new stdClass;
1046 $remoteProductSku = new stdClass;
1047 $localSlugs = new stdClass;
1048 $localProductName = new stdClass;
1049 $rmNames = [];
1050 $lcNames = [];
1051 $localProductName->name = [];
1052 $countIdsQDiferem = 0;
1053
1054 foreach($localProducts as $k=>$lp){
1055 foreach($collection as $c=>$cl){
1056 $resultSearch = FavelaMigration::searchProduct($cl);
1057
1058 if(empty($resultSearch)){
1059 $notExistsProduct[] = $resultSearch;
1060 }else{
1061 //Se existe na base local um produto correspondente ao remoto.
1062 $produtoName[$c] = "{$cl->produtoNome}, {$cl->produtoMarca}";
1063 $productSlug[$c] = $resultSearch->get_slug();
1064 $totalIds[] = $resultSearch->get_id();
1065 $remoteSlug->slug[] = $resultSearch->get_slug();
1066 $localSlugs->slug[] = $lp->get_slug();
1067 $remoteProductSku->sku[] = $resultSearch->get_sku();
1068 $localProductName->name[] = "{$lp->get_name()}, {$cl->produtoMarca}";
1069 }
1070 // && $remoteProductSku->sku[$c] == $lp->get_sku()
1071 if($lp->get_slug() == $remoteSlug->slug[$c]){
1072 echo "*Produto(Local) Nome:{$lp->get_name()}, id:{$lp->get_id()}, slug:{$lp->get_slug()},
1073 c:({$c}), sku:{$lp->get_sku()} Produto(Remoto): Nome:{$produtoName[$c]},
1074 slug:{$productSlug[$c]} ,sku:{$remoteProductSku->sku[$c]} status:[Bate com o WS
1075 id:{$totalIds[$c]}] <br>";
1076
1077
1078 echo "(ids iguais)k: {$c} | : (remotos)" . ($totalIds[$c]) . " (locais): {$lp->get_id()}<br>";
1079 $idsQBatem[] = $lp->get_id();
1080 $slugsQBatem[] = $lp->get_slug();
1081 //$totalNames[] = $resultSearch->get_name();
1082 $rmNames[] = ['name'=>$remoteName[$c], 'slug'=>$remoteSlug->slug[$c],'id'=>$totalIds[$c], 'sku'=>$remoteProductSku->sku];
1083 $lcNames[] = ['name'=>$lp->get_name(), 'slug'=>$lp->get_slug(),'id'=>$lp->get_id(), 'sku'=>$lp->get_sku()];
1084
1085 }
1086 else{
1087 echo "-Produto(Local) Nome:{$lp->get_name()}, id:{$lp->get_id()}, slug:{$lp->get_slug()},
1088 c:({$c}), sku:{$lp->get_sku()} Produto(Remoto): Nome:{$produtoName[$c]},
1089 slug:{$productSlug[$c]} ,sku:{$remoteProductSku->sku[$c]}
1090 status:[Não Bate com o WS id:{$totalIds[$c]}] <br>";
1091
1092 echo "(ids Diferem)k: {$c} | : (remotos)" . ($totalIds[$c]) . " (locais): {$lp->get_id()}<br>";
1093 $idsQDiferetem[] = $lp->get_id();
1094 $slugsQDiferem[] = $lp->get_slug();
1095 }
1096 }
1097 }
1098
1099
1100 echo "<br><b>ids Que Batem</b><br>";
1101 var_dump(count($idsQBatem));
1102 print_r($idsQBatem);
1103
1104 echo "<b>Total Ids do WebService</b><br>";
1105 //var_dump(count($totalIds));
1106 echo "<b>Total Ids Não batem com a busta de Texto</b><br>";
1107 var_dump(count($notExistsProduct));
1108
1109 echo "<b>Ids que diferem</b><br>";
1110 $result = array_unique($idsQDiferetem);
1111 //print_r($result);
1112 var_dump(count($result));
1113 print_r($result);
1114
1115 echo "<b>Diff dos 2 arrays(ids)</b><br>";
1116 //Ids que diferem | ids que batem
1117 $diffResult = array_diff($result, $idsQBatem);
1118
1119 var_dump(count($diffResult));
1120 //var_dump($diffResult);
1121
1122 echo "<b>Produtos do Diff</b><br>";
1123 print_r($diffResult);
1124 $deletedIds = $diffResult;
1125
1126 /***/
1127
1128 echo "<br><b>Slugs Que Batem</b><br>";
1129 var_dump(count($slugsQBatem));
1130 print_r($slugsQBatem);
1131
1132 echo "<b>Total Ids do WebService</b><br>";
1133 //var_dump(count($totalIds));
1134 echo "<b>Total Ids Não batem com a busta de Texto</b><br>";
1135 var_dump(count($notExistsProduct));
1136
1137 echo "<b>Slugs que diferem</b><br>";
1138 $resultSlug = array_unique($slugsQDiferem);
1139 //print_r($result);
1140 var_dump(count($resultSlug));
1141 print_r($resultSlug);
1142
1143 echo "<b>Diff dos 2 arrays(slugs)</b><br>";
1144 //Ids que diferem | ids que batem
1145 $diffResultSlug = array_diff($resultSlug, $slugsQBatem);
1146
1147 var_dump(count($diffResultSlug));
1148 //var_dump($diffResult);
1149
1150 echo "<b>Produtos do Diff</b><br>";
1151 print_r($diffResultSlug);
1152 $deletedIds = $diffResult;
1153
1154/*
1155 echo "<b>Diff das Slugs</b><br>";
1156 $diffResultSlugs = array_diff($localSlugs->slug, $remoteSlug->slug);
1157 $resultSlug = array_unique($diffResultSlugs);
1158
1159 var_dump(count($diffResultSlugs));
1160 //print_r($diffResultSlugs);
1161 echo "<b>Slug processado excluido os Repetidos</b><br>";
1162 var_dump(count($resultSlug));
1163 //var_dump($resultSlug);
1164 //var_dump($diffResultSlugs);
1165
1166
1167 echo " <b>Diff dos Nomes(locais/remotos)</b><br>";
1168 $diffResultNames = array_diff($totalNames, $remoteName);
1169 var_dump(count($diffResultNames));
1170 //print_r($diffResultNames);
1171 echo "<b>Total de nomes que Batem</b><br>";
1172 var_dump(count($totalNames));
1173
1174 echo "<b>Total de nomes do Ws</b><br>";
1175 var_dump(count($remoteName));
1176
1177 echo "<b>Remote Info Produtcs{names}</b><br>";
1178 var_dump(count($rmNames));
1179 //print_r($rmNames);
1180
1181 echo "<b>Local Info Produtcs{names}</b><br>";
1182 var_dump(count($lcNames));
1183 //print_r($lcNames);
1184 //print_r($diffResultNames);
1185*/
1186 if(isset($deletedIds)){
1187 $productNameDelIds = [];
1188 foreach($deletedIds as $d => $pDelete){
1189 $product = wc_get_product($pDelete);
1190 $productNameDelIds[] = $product->get_name();
1191 echo "Produto Não Corresponde a API Enviado para a Lixeira id[{$pDelete} | nome: {$productNameDelIds[$d]}]<br>";
1192 //wh_deleteProduct($pDelete);
1193 $product = wc_get_product($pDelete);
1194 $product->delete();
1195 $result = 'trash' === $product->get_status();
1196
1197 if (!$result)
1198 {
1199 return new WP_Error(999, sprintf(__('This %s cannot be deleted', 'woocommerce'), 'product'));
1200 }
1201 }
1202 }
1203
1204
1205
1206
1207 //61
1208 //FavelaMigration::init($prodPosition=61);
1209 //186
1210 /*
1211 $bate = 0;
1212 foreach($collection as $k=> $coll){
1213
1214 //FavelaMigration::init($prodPosition=185);
1215 //echo "no loop: {$i}";
1216 //$productsOp[] = FavelaMigration::init($i);
1217
1218 $productTeste = $coll;
1219 $resultSearch = FavelaMigration::searchProduct($productTeste);
1220 if(empty($resultSearch)){
1221 echo "<h4>Produto não existe na base Local</h4>";
1222
1223 }else{
1224 $totalIds[] = $resultSearch->get_id();
1225 //echo "<h4>Produto existe na base Local</h2>";
1226 //var_dump($resultSearch);
1227 }
1228
1229 $produtoName = "{$coll->produtoNome}, {$coll->produtoMarca}";
1230
1231 foreach($totalIds as $t=>$tIds){
1232 if($localProducts[$t]->get_id() == $tIds){
1233 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>";
1234 $bate++;
1235 //echo "(ids iguais) k: {$k} | t: [{$t}] : ids remoto: " . ($tIds) . " ids local: {$localProducts[$t]->get_id()} <br>";
1236 echo "(ids iguais)k: {$k} | t: [{$t}] : (remotos)" . ($tIds) . " (locais): {$localProducts[$t]->get_id()}<br>";
1237 //unset($lp);
1238 //$listVerify['produtoBate'] = $localProducts[$prodPosition];
1239 //$listNoExists = $lp;
1240 }else{
1241
1242 //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>";
1243
1244 //unset($localProducts);
1245 echo "(ids diferentes)k: {$k} | t: [{$t}] : (remotos)" . ($tIds) . " (locais): {$localProducts[$t]->get_id()}<br>";
1246 }
1247 }
1248
1249 //echo "<h4>Total de produtos Locais</h4>";
1250
1251
1252 }*/
1253
1254 //print_r($listVerify);
1255 //print_r($totalIds);
1256
1257
1258 //return $listVerify;
1259
1260
1261
1262 //echo "<h4>Produtos Operacionais</h4>";
1263 //print_r($productsOp);
1264 //var_dump($productsOp["produtoBate"]);
1265}
1266
1267class MigrationRules {
1268
1269 private static $lproduct, $rproduct, $collection,
1270 $postId, $prodPosition, $productTeste, $remoteAttr;
1271
1272 private static $tamanhoUpdated = false;
1273 private static $isUpdated = false;
1274
1275 static function filterVariations($post_id,$meta_key,$meta_value) {
1276 $query = new \WP_Query( array(
1277 'post_parent' => $post_id,
1278 'post_status' => 'publish',
1279 'post_type' => 'product_variation',
1280 'posts_per_page' => -1,
1281 'meta_query' => array( array(
1282 'key' => $meta_key,
1283 'value' => $meta_value,
1284 ) ),
1285 ) );
1286 $result = array();
1287 if($query->have_posts()){
1288 while ($query->have_posts()) {
1289 $query->next_post();
1290 $result[] = $query->post;
1291 }
1292 wp_reset_postdata();
1293 }
1294 wp_reset_query();
1295
1296 return $result;
1297 }
1298/*
1299*
1300
1301**/
1302 static function _filterVariations($post_id,array $properties) {
1303 $query = new \WP_Query( array(
1304 'post_parent' => $post_id,
1305 'post_status' => 'publish',
1306 'post_type' => 'product_variation',
1307 'posts_per_page' => -1,
1308 'meta_query' => array(
1309 'relation' => 'AND',
1310 'cor_clause' => array(
1311 'key' => $properties['cor_key'],
1312 'value' => $properties['cor_value'],
1313 ),
1314 'tamanho_clause' => array(
1315 'key' => $properties['tamanho_key'],
1316 'value' => $properties['tamanho_value'],
1317 ),
1318 ),
1319 ) );
1320 $result = array();
1321 if($query->have_posts()){
1322 while ($query->have_posts()) {
1323 $query->next_post();
1324 $result[] = $query->post;
1325 }
1326 wp_reset_postdata();
1327 }
1328 wp_reset_query();
1329
1330 return $result;
1331 }
1332
1333 static function storeStock($listCorT, $x){
1334 $rtotal = self::getTotalRemoteProducts(); //trata os dados do estoque
1335
1336 if(strlen($listCorT->produtoQtdeEstoque) <= 4){
1337 $_stockRemote = (int)substr($listCorT->produtoQtdeEstoque,0,1);
1338 } else{
1339 $_stockRemote = (int)substr($listCorT->produtoQtdeEstoque,0,2);
1340 }
1341
1342 echo "{Cor:[{$listCorT->produtoCor}], Tamanho:[{$listCorT->produtoTamanho}] Será persistido} | (x:{$x},total:{$rtotal}) | <br>";
1343 $variation_data = [
1344 'attributes' => [
1345 'cor' => $listCorT->produtoCor,
1346 'tamanho' => $listCorT->produtoTamanho,
1347 ],
1348 'sku' => MigrationRules::getProductTeste()->produtoId,
1349 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1350 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1351 'stock_qty' => $_stockRemote
1352 ];
1353 // The function to be run
1354 _create_product_variation(MigrationRules::getPostId(), $variation_data );
1355 }
1356
1357 static function updateStock($listCorT, $attrCor, $attrTamanho, $attrStock, $x, $c, $cproducts){
1358 $rtotal = self::getTotalRemoteProducts(); //trata os dados do estoque
1359 $totalL = self::getTotalLocalProducts();
1360 $diffProducts = $rtotal-$totalL;
1361
1362 if(strlen($listCorT->produtoQtdeEstoque) <= 4){
1363 $_stockRemote = (int)substr($listCorT->produtoQtdeEstoque,0,1);
1364 } else{
1365 $_stockRemote = (int)substr($listCorT->produtoQtdeEstoque,0,2);
1366 }
1367
1368 $pcor = strtolower(tirarAcentos($listCorT->produtoCor));
1369 $acor = strtolower(tirarAcentos($attrCor));
1370
1371 $corFragment = explode(" ", $pcor);
1372
1373 if(isset($corFragment[0])){
1374 $pcor = $corFragment[0];
1375 }
1376
1377 if(isset($corFragment[1])){
1378 $pcor = $corFragment[0] . "-" . $corFragment[1];
1379 }
1380
1381
1382 $rTamanho = strtolower(tirarAcentos($listCorT->produtoTamanho));
1383 $atTamanho = strtolower(tirarAcentos($attrTamanho));
1384
1385 if($pcor == $acor){
1386 //atualiza
1387 echo "produtoCor:[{$pcor}] são iguais AttrCor:[{$acor}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
1388 //se o tamanho do produto for igual
1389 if($rTamanho == $attrTamanho){
1390 //atualiza
1391 echo "produtoTamanho:[{$rTamanho}] são iguais attrTamanho:[{$atTamanho}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
1392
1393 //se o estoque remoto for igual ao estoque local (Não atualiza)
1394 if($_stockRemote == $attrStock){
1395 //não atualiza
1396 echo "produtoQtdeEstoque:[{$_stockRemote}] são iguais{NÃO ATUALIZA} attrStock:[{$attrStock}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
1397 echo "<hr><hr>";
1398 //self::$isUpdated = true;
1399 }
1400
1401 //se estoque remoto for maior que o estoque local (Atualiza)
1402 if($_stockRemote > $attrStock){
1403 //atualiza
1404 //var_dump(self::$isUpdated);
1405
1406 echo "condition:(<i>produto tem cor e tamanho iguais e estoque local menor do que o estoque remoto</i>:)
1407 ,<br> produtoQtdeEstoque(Remoto):[{$_stockRemote}] {ATUALIZA} -> attrStock:[{$attrStock}] ({$x}-{$c}) variable_id:[$cproducts] [{{$_stockRemote}} > {{$attrStock}}] <br>";
1408 $result = MigrationRules::filterVariations(MigrationRules::getPostId(), 'attribute_pa_tamanho',$rTamanho);
1409
1410 $variation_data = [
1411 'attributes' => [
1412 'cor' => $listCorT->produtoCor,
1413 'tamanho' => $listCorT->produtoTamanho,
1414 ],
1415 'ID' => $cproducts,
1416 'sku' => MigrationRules::getProductTeste()->produtoId,
1417 'update' => true,
1418 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1419 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1420 'stock_qty' => $_stockRemote
1421 ];
1422 // The function to be run
1423 _create_product_variation(MigrationRules::getPostId(), $variation_data );
1424 //self::$isUpdated = true;
1425
1426
1427 }
1428 if($_stockRemote < $attrStock){//se for diferente, atualiza com base no valor do estoque remoto
1429 //atualiza
1430 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>";
1431 echo "<hr><hr>";
1432 $localStk = (int)get_post_meta($cproducts, '_stock', true );
1433 //var_dump($localStk);
1434
1435 $variation_data = [
1436 'attributes' => [
1437 'cor' => $listCorT->produtoCor,
1438 'tamanho' => $listCorT->produtoTamanho,
1439 ],
1440 'ID' => $cproducts,
1441 'sku' => MigrationRules::getProductTeste()->produtoId,
1442 'update' => true,
1443 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1444 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1445 'stock_qty' => $_stockRemote + $localStk
1446 ];
1447 // The function to be run
1448 _create_product_variation(MigrationRules::getPostId(), $variation_data );
1449 //self::$isUpdated = true;
1450
1451 }
1452 }elseif(($totalL)-1 == $c && $totalL < $rtotal){//se tamanhos são diferentes
1453 // [se a quantidade de produtos com cores iguais e tamanhos diferentes
1454 // _remotos_ forem maior que a quantidade de produtos locais (insere ou atualiza)
1455 echo "produtoTamanho:[{$rTamanho}] são diferentes attrTamanho:[{$atTamanho}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
1456 $result = MigrationRules::_filterVariations(MigrationRules::getPostId(),
1457 ['cor_key'=>'attribute_pa_cor',
1458 'cor_value'=>$pcor,'tamanho_key'=>'attribute_pa_tamanho', 'tamanho_value'=>$rTamanho
1459 ]);
1460
1461 //var_dump($result);
1462
1463 if(empty($result)){
1464 //var_dump($result);
1465 // The variation data
1466 echo "{Tamanho remoto não existe - Tamanho [{$rTamanho}] Será persistido} | (x:{$x}, c:{$c},total:{$rtotal}) - variable_id:[$cproducts] | <br>";
1467 $variation_data = [
1468 'attributes' => [
1469 'cor' => $listCorT->produtoCor,
1470 'tamanho' => $listCorT->produtoTamanho,
1471 ],
1472 'sku' => MigrationRules::getProductTeste()->produtoId,
1473 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1474 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1475 'stock_qty' => $_stockRemote
1476 ];
1477 // The function to be run
1478 _create_product_variation(MigrationRules::getPostId(), $variation_data );
1479 }
1480 else{
1481
1482 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>";
1483 /*$variation_data = [
1484 'attributes' => [
1485 'cor' => $listCorT->produtoCor,
1486 'tamanho' => $listCorT->produtoTamanho,
1487 ],
1488 'ID' => $cproducts,
1489 'sku' => MigrationRules::getProductTeste()->produtoId,
1490 'update' => true,
1491 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1492 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1493 'stock_qty' => $_stockRemote
1494 ];
1495 */
1496 //_create_product_variation(MigrationRules::getPostId(), $variation_data );
1497
1498
1499 }
1500 }
1501 //se a quantidade do estoque for igual
1502 //var_dump(substr($listCorT->produtoQtdeEstoque,0,1));
1503
1504 }else{//atualiza $c (contador do loop das variacoes remotas)
1505 $totalL = self::getTotalLocalProducts();
1506 $diffProducts = $rtotal-$totalL;
1507 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>";
1508 //se total de variacoes locais é menor que o total de variacoes remotas
1509 //insere a variacao remota até a quantidade de variacoes locais ficar = a quantidade de variacoes
1510 //remotas
1511 //enquanto 29 <= 52 { execulta }
1512 // $c < $rtotal && $z <= $rtotal && { $z = $c; store(color); $z++;}
1513 //$z = $c;
1514 //30 == $c
1515 //se o contador de produtos locais ficar com o mesmo valor do total de produtos locais tornarem iguais
1516 //e a quantidade de produtos locais for menor que o total de produtos remotos persiste o produto remoto
1517 if(($totalL)-1 == $c && $totalL < $rtotal){
1518 //if($z <= $rtotal){
1519 //$pID = MigrationRules::getPostId();
1520 //$result = MigrationRules::filterVariations(MigrationRules::getPostId(), 'attribute_pa_cor',$pcor);
1521 //$resultT = MigrationRules::filterVariations(MigrationRules::getPostId(), 'attribute_pa_tamanho',$listCorT->produtoTamanho);
1522 //echo "produtoTamanho:[{$rTamanho}] são diferentes attrTamanho:[{$atTamanho}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
1523 $result = MigrationRules::_filterVariations(MigrationRules::getPostId(),
1524 ['cor_key'=>'attribute_pa_cor',
1525 'cor_value'=>$pcor,'tamanho_key'=>'attribute_pa_tamanho', 'tamanho_value'=>$rTamanho
1526 ]);
1527
1528 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>";
1529
1530 //var_dump($result);
1531 if(empty($result)){
1532 //var_dump($result);
1533 // The variation data
1534 echo "{Cor remota não existe - Cor [{$pcor}] Será persistida} |Tamanho:{$listCorT->produtoTamanho} (x:{$x}, c:{$c},total:{$rtotal}) - variable_id:[$cproducts] | <br>";
1535 $variation_data = [
1536 'attributes' => [
1537 'cor' => $listCorT->produtoCor,
1538 'tamanho' => $listCorT->produtoTamanho,
1539 ],
1540 'sku' => MigrationRules::getProductTeste()->produtoId,
1541 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1542 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1543 'stock_qty' => $_stockRemote
1544 ];
1545 // The function to be run
1546 _create_product_variation(MigrationRules::getPostId(), $variation_data );
1547 //$z++;
1548 }
1549 else{
1550 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>";
1551 //echo "produtoTamanho:[{$rTamanho}] são diferentes attrTamanho:[{$atTamanho}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
1552 $result = MigrationRules::_filterVariations(MigrationRules::getPostId(),
1553 ['cor_key'=>'attribute_pa_cor',
1554 'cor_value'=>$pcor,'tamanho_key'=>'attribute_pa_tamanho', 'tamanho_value'=>$rTamanho
1555 ]);
1556 //var_dump($result[0]->ID);
1557
1558 //if(empty($result)){
1559 //var_dump($result);
1560 // The variation data
1561 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>";
1562 $variation_data = [
1563 'attributes' => [
1564 'cor' => $listCorT->produtoCor,
1565 'tamanho' => $listCorT->produtoTamanho,
1566 ],
1567 'sku' => MigrationRules::getProductTeste()->produtoId,
1568 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1569 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1570 'stock_qty' => $_stockRemote
1571 ];
1572 // The function to be run
1573 //_create_product_variation(MigrationRules::getPostId(), $variation_data );
1574
1575 #
1576 //echo "{Cor remota existe - Cor [{$pcor}] Será Atualizada} |Tamanho:{$listCorT->produtoTamanho} (x:{$x}, c:{$c},total:{$rtotal}) - variable_id:[$cproducts] | <br>";
1577 /*
1578 $variation_data = [
1579 'attributes' => [
1580 'cor' => $listCorT->produtoCor,
1581 'tamanho' => $listCorT->produtoTamanho,
1582 ],
1583 'ID' => $cproducts,
1584 'sku' => MigrationRules::getProductTeste()->produtoId,
1585 'update' => true,
1586 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1587 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1588 'stock_qty' => $_stockRemote
1589 ];
1590 // The function to be run
1591 _create_product_variation(MigrationRules::getPostId(), $variation_data );
1592 */
1593 }
1594
1595
1596 }else{
1597 //echo ">produtoCor:[{$pcor}] são diferentes AttrCor:[{$acor}] ({$x}-{$c}) variable_id:[$cproducts] | <br>";
1598 }
1599
1600 }
1601 //exit;
1602 }
1603
1604 static function setTotalLocalProducts($lproduct){
1605 self::$lproduct = $lproduct;
1606 }
1607
1608 static function setTotalRemoteProducts($rproduct){
1609 self::$rproduct = $rproduct;
1610 }
1611
1612
1613 static function getTotalLocalProducts(){
1614 return self::$lproduct;
1615 }
1616
1617 static function getTotalRemoteProducts(){
1618 return self::$rproduct;
1619 }
1620
1621 static function setCollection($collection){
1622 self::$collection = $collection;
1623 }
1624
1625 static function getCollection(){
1626 return self::$collection;
1627 }
1628
1629
1630 static function setPostId($postId){
1631 self::$postId = $postId;
1632 }
1633
1634 static function getPostId(){
1635 return self::$postId;
1636 }
1637
1638 static function setProdPosition($prodPosition){
1639 self::$prodPosition = $prodPosition;
1640 }
1641
1642 static function getProdPosition(){
1643 return self::$prodPosition;
1644 }
1645
1646 static function setProductTeste($productTeste){
1647 self::$productTeste = $productTeste;
1648 }
1649
1650 static function getProductTeste(){
1651 return self::$productTeste;
1652 }
1653
1654 static function setRemoteAttr($remoteAttr){
1655 self::$remoteAttr = $remoteAttr;
1656 }
1657
1658 static function getRemoteAttr(){
1659 return self::$remoteAttr;
1660 }
1661
1662}
1663
1664class FavelaMigration {
1665
1666 static function listAllVariableProducts($post_id){
1667 //cria uma instancia do produto
1668 $product = wc_get_product($post_id);
1669
1670 //pega todas as variacoes do produto (só os ids)
1671 if(!empty($product)){
1672 $current_products = $product->get_children();
1673 return(count($current_products));
1674 }
1675
1676 }
1677
1678 static function getAllVariableProduct($post_id){
1679 //cria uma instancia do produto
1680 $product = wc_get_product($post_id);
1681 if(!empty($product)){
1682 $current_products = $product->get_children();
1683 return $current_products;
1684 }
1685 }
1686
1687 static function getAllRemoteVariableProduct(stdClass $collection){
1688 return(count($collection->listaCorTamanho));
1689 }
1690
1691 static function getAllRemoteVariableProductNames(stdClass $collection){
1692 foreach($collection->listaCorTamanho as $k=>$coll){
1693 echo "{$coll->produtoCor},{$coll->produtoTamanho} -({$k})<br>";
1694 }
1695 }
1696
1697
1698 static function getAttributesForProduct(stdClass $product){
1699 foreach($product->listaCorTamanho as $p=>$prop){
1700 $cores[] = $prop->produtoCor;
1701 $tamanho[] = $prop->produtoTamanho;
1702 $stock[] = $prop->produtoQtdeEstoque;
1703 }
1704
1705 return array('cores'=>$cores, 'tamanho'=>$tamanho, 'estoque'=>$stock);
1706 }
1707
1708 static function _getAttributesForProduct(stdClass $product){
1709 //echo "<h1>Objeto Remoto como stdClass: </h1>";
1710 //var_dump($product->listaCorTamanho);
1711 //$c = 0;
1712 foreach($product->listaCorTamanho as $p=>$prop){
1713 //$object = $object[$k];
1714 foreach($prop as $k=>$value){
1715 //$attributeMeta[] = $prop->$k;
1716 //$object[] = ["{$k}"=>[$prop->$k]];
1717 //echo "p:[{$p}] k:[{$k}] count:[{$c}] value:[{$value}]<br>";
1718 $attribute = substr($k,7);//produto{AttrName}elimina produto da str
1719 if("QtdeEstoque" != $attribute){
1720 $object[$attribute][] = $product->listaCorTamanho[$p]->$k;
1721 }
1722
1723 }
1724 //echo "<h3>{$product->listaCorTamanho[$p]->$attribute} [{$attribute}]</h3>";
1725 $c++;
1726 }
1727
1728 //var_dump($object);
1729
1730 return $object;
1731 //return array('cores'=>$cores, 'tamanho'=>$tamanho, 'estoque'=>$stock);
1732 }
1733
1734 static function getAllAttributes($post_id){
1735 //exibe os atributos do produto
1736 $prodAttrGlobal = get_post_meta($post_id, '_product_attributes', true );
1737 echo "<h2>Atributos do produto</h2>";
1738 var_dump($prodAttrGlobal);
1739 }
1740
1741 static function getAllAttrForTaxonomy($tax,$post_id){
1742 echo "<h2>termos dos atributos dos produtos(pa_tamanho)</h2>";
1743 $result = woocommerce_get_product_terms($post_id, $tax, 'names');
1744 var_dump($result);
1745 }
1746
1747 static function updateVariableProduct(stdClass $productTeste, array $current_products){
1748 //counters
1749 MigrationRules::setTotalLocalProducts(count($current_products));
1750 MigrationRules::setTotalRemoteProducts(count($productTeste->listaCorTamanho));
1751
1752 $x = 0; $c=0;
1753 //loop (produto remoto / produtos variavies)
1754 foreach($productTeste->listaCorTamanho as $l=>$listCorT){
1755 foreach($current_products as $c=>$cproducts){
1756 $attrCor = get_post_meta($cproducts, 'attribute_pa_cor', true );
1757 //var_dump($attrCor);
1758 $attrTamanho = get_post_meta($cproducts, 'attribute_pa_tamanho', true );
1759 $attrStock = get_post_meta($cproducts, '_stock', true );
1760 //atualiza estoque
1761 MigrationRules::updateStock($listCorT, $attrCor, $attrTamanho, $attrStock, $x, $c, $cproducts);
1762 $x++;//no loop das variacoes locais ($current_products)
1763 }
1764 $c++;//no loop das variacoes remotas ($productTest)
1765 }
1766 }
1767
1768
1769 static function storeVariableProduct(stdClass $productTeste){
1770 //counters
1771 MigrationRules::setTotalRemoteProducts(count($productTeste->listaCorTamanho));
1772 $c=0;
1773 //loop (produto remoto / produtos variavies)
1774 foreach($productTeste->listaCorTamanho as $l=>$listCorT){
1775 MigrationRules::storeStock($listCorT, $c);
1776 $c++;//no loop das variacoes remotas ($productTest)
1777 }
1778 }
1779
1780 static function searchProduct($productTeste){
1781 $result = get_wc_product_by_title($productTeste->produtoNome, $productTeste->produtoMarca);
1782 return $result;
1783 }
1784
1785 static function getAllLocalProducts(){
1786 // Get 10 most recent product IDs in date descending order.
1787 $query = new WC_Product_Query( array(
1788 'limit' => 209,
1789 'orderby' => 'date',
1790 'order' => 'ASC',
1791 ));
1792 $products = $query->get_products();
1793 return $products;
1794 }
1795
1796 static function init($prodPosition){
1797 //recebe uma coleção remota
1798 $collection = getProdutosForWikiWs();
1799 $productTeste = $collection[$prodPosition];
1800 //se colecao for vazia sai do funcao
1801 if(empty($productTeste)){
1802 return;
1803 }
1804
1805 //Busca com base no {titulo}, {nomeDaMarca} na base da loja
1806 //caso exista um produto local com o mesmo nome de um produto remoto.
1807 $resultSearch = self::searchProduct($productTeste);
1808
1809 if(empty($resultSearch)){
1810 echo "<h4>Produto não existe na base Local</h4>";
1811 $pRemotosQNaoExistemLocal[] = $productTeste->produtoNome;
1812 }else{
1813 $totalIds[] = $resultSearch->get_id();
1814 echo "<h4>Produto existe na base Local</h2>";
1815 //var_dump($resultSearch);
1816 }
1817
1818 $pRemotos = self::getAllRemoteVariableProduct($productTeste);
1819 echo "<h2>Total de produtos Variáveis Remotos: <i>[{$pRemotos}]</i></h2>";
1820 //todos os nomes das variáveis remotas
1821 self::getAllRemoteVariableProductNames($productTeste);
1822
1823 //busca os produtos locais baseados no sku = WebService.produtoTest.id
1824 $post_id = wc_get_product_id_by_sku($productTeste->produtoId);
1825
1826 //caso
1827 /*if(!empty($post_id)){
1828 update_post_meta($post_id, '_sku', $productTeste->produtoId, true);
1829 echo "<h2>SKU do produto Manipulado</h2><br>";
1830 var_dump($post_id);
1831 }*/
1832 //var_dump($produtoTeste);
1833 //pega os atributosdo produto remoto (taxonomias e termos)
1834 //$remoteAttributes = self::getAttributesForProduct($productTeste);
1835 $remoteAttributes = self::_getAttributesForProduct($productTeste);
1836 echo "<h1>Array de atributos remotos construido:</h1>";
1837 var_dump($remoteAttributes);
1838
1839 if($post_id != 0){
1840 update_product_variation( array(
1841 'ID' => $post_id,
1842 'author' => '', // optional
1843 'title' => "{$productTeste->produtoNome}, {$productTeste->produtoMarca}",
1844 'content' => "{$productTeste->produtoNome} - {$productTeste->produtoDescricao} - {$productTeste->produtoMarca} - {$productTeste->produtoCaracteristicas}" ,
1845 'excerpt' => $productTeste->produtoDescricao,
1846 'regular_price' => $productTeste->produtoPrecoBase, // product regular price
1847 'sale_price' => $productTeste->produtoPrecoPromo, // product sale price (optional)
1848 'stock' => $collection[$prodPosition]->listaCorTamanho[0]->produtoQtdeEstoque,
1849 'manager_stock' => '0',
1850 'category' => $productTeste->produtoCat,
1851 // Set a minimal stock quantity
1852 'image_id' => '', // optional
1853 'gallery_ids' => array(), // optional
1854 'sku' => $productTeste->produtoId, // optional
1855 'tax_class' => '', // optional
1856 'weight' => $productTeste->produtoPeso, // optional
1857 'width' => $productTeste->produtoDimensaoL,
1858 'length' => $productTeste->produtoDimensaoC,
1859 // For NEW attributes/values use NAMES (not slugs)
1860 'attributes' => $remoteAttributes,
1861 ));
1862 }else{
1863 //var_dump($produtoTeste);
1864 $post_id = update_product_variation( array(
1865 'author' => '', // optional
1866 'title' => "{$productTeste->produtoNome}, {$productTeste->produtoMarca}",
1867 'content' => "{$productTeste->produtoNome} - {$productTeste->produtoDescricao} - {$productTeste->produtoMarca} - {$productTeste->produtoCaracteristicas}" ,
1868 'excerpt' => $productTeste->produtoDescricao,
1869 'category' => $productTeste->produtoCat,
1870 'regular_price' => $productTeste->produtoPrecoBase, // product regular price
1871 'sale_price' => $productTeste->produtoPrecoPromo, // product sale price (optional)
1872 'stock' => $collection[$prodPosition]->listaCorTamanho[0]->produtoQtdeEstoque,
1873 'manager_stock' => '0',
1874 // Set a minimal stock quantity
1875 'image_id' => '', // optional
1876 'gallery_ids' => array(), // optional
1877 'sku' => $productTeste->produtoId, // optional
1878 'tax_class' => '', // optional
1879 'weight' => $productTeste->produtoPeso, // optional
1880 'width' => $productTeste->produtoDimensaoL,
1881 'length' => $productTeste->produtoDimensaoC,
1882 // For NEW attributes/values use NAMES (not slugs)
1883 'attributes' => $remoteAttributes,
1884 ) );
1885 }
1886 //exit;
1887
1888 //lista todos os produtos variáveis.
1889 echo "<h1>Total de Variações Locais</h1>";
1890 var_dump(self::listAllVariableProducts($post_id));
1891
1892 //exibe todos os attributos
1893 self::getAllAttributes($post_id);
1894
1895 //exibe todos os termos (por taxonomia)
1896 self::getAllAttrForTaxonomy($tax='pa_cor',$post_id);
1897
1898 //retorna um array contendo todos os ids de produtos variáveis
1899 $current_products = self::getAllVariableProduct($post_id);
1900 //atualiza a loja com base nas informacoes dos produtos variaveis do WS
1901 MigrationRules::setCollection($collection);
1902 MigrationRules::setPostId($post_id);
1903 MigrationRules::setProdPosition($prodPosition);
1904 MigrationRules::setProductTeste($productTeste);
1905 MigrationRules::setRemoteAttr($remoteAttributes);
1906
1907 //post_id, $collection, prodposition, productTeste, remoteAttr
1908 if(empty($current_products)){
1909 self::storeVariableProduct($productTeste);
1910 }
1911 else{
1912 self::updateVariableProduct($productTeste,$current_products);
1913 }
1914
1915
1916 }
1917}
1918
1919function createTerms($post_id, $attributes_data){
1920 if( sizeof($attributes_data) > 0 ){
1921 $attributes = array(); // Initializing
1922
1923 // Loop through defined attribute data
1924 foreach( $attributes_data as $key => $attribute_array ) {
1925 if( isset($attribute_array['name']) && isset($attribute_array['options']) ){
1926 // Clean attribute name to get the taxonomy
1927 $taxonomy = 'pa_' . wc_sanitize_taxonomy_name( $attribute_array['name'] );
1928
1929 $option_term_ids = array(); // Initializing
1930
1931 // Loop through defined attribute data options (terms values)
1932 foreach( $attribute_array['options'] as $option ){
1933 if( term_exists( $option, $taxonomy ) ){
1934 // Save the possible option value for the attribute which will be used for variation later
1935 wp_set_object_terms($post_id, $option, $taxonomy, true );
1936 // Get the term ID
1937 $option_term_ids[] = get_term_by( 'name', $option, $taxonomy )->term_id;
1938 }else{
1939 //wp_set_object_terms($post_id, $option, $taxonomy, true );
1940 //$option_term_ids[] = get_term_by( 'name', $option, $taxonomy )->term_id;
1941 //var_dump($option_term_ids);
1942 }
1943 }
1944 }
1945
1946 // Loop through defined attribute data
1947 $attributes[$taxonomy] = array(
1948 'name' => $taxonomy,
1949 'value' => $option_term_ids, // Need to be term IDs
1950 'position' => $key + 1,
1951 'is_visible' => $attribute_array['visible'],
1952 'is_variation' => $attribute_array['variation'],
1953 'is_taxonomy' => '1'
1954 );
1955 }
1956 // Save the meta entry for product attributes
1957 update_post_meta( $post_id, '_product_attributes', $attributes);
1958
1959 }
1960}
1961
1962function create_product_attribute( $label_name ){
1963 global $wpdb;
1964
1965 $slug = sanitize_title( $label_name );
1966
1967 if ( strlen( $slug ) >= 28 ) {
1968 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 ) );
1969 } elseif ( wc_check_if_attribute_name_is_reserved( $slug ) ) {
1970 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 ) );
1971 } elseif ( taxonomy_exists( wc_attribute_taxonomy_name( $label_name ) ) ) {
1972 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 ) );
1973 }
1974
1975 $data = array(
1976 'attribute_label' => $label_name,
1977 'attribute_name' => $slug,
1978 'attribute_type' => 'select',
1979 'attribute_orderby' => 'menu_order',
1980 'attribute_public' => 0, // Enable archives ==> true (or 1)
1981 );
1982
1983 $results = $wpdb->insert( "{$wpdb->prefix}woocommerce_attribute_taxonomies", $data );
1984
1985 if ( is_wp_error( $results ) ) {
1986 return new WP_Error( 'cannot_create_attribute', $results->get_error_message(), array( 'status' => 400 ) );
1987 }
1988
1989 $id = $wpdb->insert_id;
1990
1991 do_action('woocommerce_attribute_added', $id, $data);
1992
1993 wp_schedule_single_event( time(), 'woocommerce_flush_rewrite_rules' );
1994
1995 delete_transient('wc_attribute_taxonomies');
1996}
1997
1998/**
1999 * Save a new product attribute from his name (slug).
2000 *
2001 * @since 3.0.0
2002 * @param string $name | The product attribute name (slug).
2003 * @param string $label | The product attribute label (name).
2004 */
2005function save_product_attribute_from_name( $name, $label='', $set=true ){
2006 if( ! function_exists ('get_attribute_id_from_name') ) return;
2007
2008 global $wpdb;
2009
2010 $label = $label == '' ? ucfirst($name) : $label;
2011 $attribute_id = get_attribute_id_from_name( $name );
2012
2013 if( empty($attribute_id) ){
2014 $attribute_id = NULL;
2015 } else {
2016 $set = false;
2017 }
2018 $args = array(
2019 'attribute_id' => $attribute_id,
2020 'attribute_name' => $name,
2021 'attribute_label' => $label,
2022 'attribute_type' => 'select',
2023 'attribute_orderby' => 'menu_order',
2024 'attribute_public' => 0,
2025 );
2026
2027 if( empty($attribute_id) ) {
2028 $wpdb->insert( "{$wpdb->prefix}woocommerce_attribute_taxonomies", $args );
2029 set_transient( 'wc_attribute_taxonomies', false );
2030 }
2031
2032 if( $set ){
2033 $attributes = wc_get_attribute_taxonomies();
2034 $args['attribute_id'] = get_attribute_id_from_name( $name );
2035 $attributes[] = (object) $args;
2036 //print_r($attributes);
2037 set_transient( 'wc_attribute_taxonomies', $attributes );
2038 } else {
2039 return;
2040 }
2041}
2042
2043/**
2044 * Get the product attribute ID from the name.
2045 *
2046 * @since 3.0.0
2047 * @param string $name | The name (slug).
2048 */
2049function get_attribute_id_from_name( $name ){
2050 global $wpdb;
2051 $attribute_id = $wpdb->get_col("SELECT attribute_id
2052 FROM {$wpdb->prefix}woocommerce_attribute_taxonomies
2053 WHERE attribute_name LIKE '$name'");
2054 return reset($attribute_id);
2055}
2056
2057/**
2058 * Create a new variable product (with new attributes if they are).
2059 * (Needed functions:
2060 *
2061 * @since 3.0.0
2062 * @param array $data | The data to insert in the product.
2063 */
2064
2065function create_product_variation( $data ){
2066 if( ! function_exists ('save_product_attribute_from_name') ) return;
2067
2068 $postname = sanitize_title( $data['title'] );
2069 $author = empty( $data['author'] ) ? '1' : $data['author'];
2070
2071 $post_data = array(
2072 'post_author' => $author,
2073 'post_name' => $postname,
2074 'post_title' => $data['title'],
2075 'post_content' => $data['content'],
2076 'post_excerpt' => $data['excerpt'],
2077 'post_status' => 'publish',
2078 'ping_status' => 'closed',
2079 'post_type' => 'product_variation',
2080 'post_parent' => $data['parent_id'],
2081 'guid' => home_url( '/product/'.$postname.'/' ),
2082 );
2083
2084 // Creating the product (post data)
2085 //$product_id = wp_insert_post( );
2086 $result = wp_insert_post( $post_data );
2087
2088 if ( $result && ! is_wp_error( $result ) ) {
2089 $product_id = $result;
2090 // Do something else
2091 var_dump($result);
2092 echo "sucesso";
2093 }else{
2094 echo "erro ao gravar produto variavel";
2095 var_dump($result);
2096 }
2097 // Get an instance of the WC_Product_Variable object and save it
2098 $product = new WC_Product_Variation( $product_id );
2099
2100 ## ---------------------- Other optional data ---------------------- ##
2101 ## (see WC_Product and WC_Product_Variable setters methods)
2102
2103 // THE PRICES (No prices yet as we need to create product variations)
2104
2105 // IMAGES GALLERY
2106 // Prices
2107 if( empty( $data['sale_price'] ) ){
2108 $product->set_price( $data['regular_price'] );
2109 } else {
2110 $product->set_price($data['sale_price'] );
2111 $product->set_sale_price($data['sale_price'] );
2112 }
2113 $variation->set_regular_price($data['regular_price'] );
2114
2115 if( ! empty( $data['gallery_ids'] ) && count( $data['gallery_ids'] ) > 0 )
2116 $product->set_gallery_image_ids( $data['gallery_ids'] );
2117
2118 // SKU/*
2119// if( ! empty( $data['sku'] ) )
2120 // $product->set_sku( $data['sku'] );
2121
2122
2123 // STOCK (stock will be managed in variations)
2124 $product->set_stock_quantity($data['stock']); // Set a minimal stock quantity
2125 if($data['manager_stock'] == '0'){
2126 $product->set_manage_stock(false);
2127 }else{
2128 $product->set_manage_stock(true);
2129 }
2130
2131 $product->set_stock_status('');
2132
2133 // Tax class
2134 if( empty( $data['tax_class'] ) )
2135 $product->set_tax_class( $data['tax_class'] );
2136
2137 // WEIGHT
2138 if( ! empty($data['weight']) )
2139 $product->set_weight(''); // weight (reseting)
2140 else
2141 $product->set_weight($data['weight']);
2142
2143 $product->validate_props(); // Check validation
2144
2145 ## ---------------------- VARIATION ATTRIBUTES ---------------------- ##
2146
2147 $product_attributes = array();
2148
2149 foreach( $data['attributes'] as $key => $terms ){
2150 $taxonomy = wc_attribute_taxonomy_name($key); // The taxonomy slug
2151 $attr_label = ucfirst($key); // attribute label name
2152 $attr_name = ( wc_sanitize_taxonomy_name($key)); // attribute slug
2153
2154 // NEW Attributes: Register and save them
2155 if( ! taxonomy_exists( $taxonomy ) )
2156 save_product_attribute_from_name( $attr_name, $attr_label );
2157
2158 $product_attributes[$taxonomy] = array (
2159 'name' => $taxonomy,
2160 'value' => '',
2161 'position' => '',
2162 'is_visible' => 0,
2163 'is_variation' => 1,
2164 'is_taxonomy' => 1
2165 );
2166
2167 foreach( $terms as $value ){
2168 $term_name = ucfirst($value);
2169 $term_slug = sanitize_title($value);
2170
2171 // Check if the Term name exist and if not we create it.
2172 if( ! term_exists( $value, $taxonomy ) )
2173 wp_insert_term( $term_name, $taxonomy, array('slug' => $term_slug ) ); // Create the term
2174
2175 // Set attribute values
2176 wp_set_post_terms( $product_id, $term_name, $taxonomy, true );
2177 }
2178 }
2179 update_post_meta( $product_id, '_product_attributes', $product_attributes );
2180
2181 $product->save(); // Save the data
2182}
2183
2184function get_product_category($catname){
2185 if($catname == ''){
2186 $catname = "CAMISAS";
2187 }else{
2188 $catnamesub = $catname;
2189 $slug = $catnamesub;
2190 //var_dump($slug);
2191 $productCategory = get_term_by( 'name', $slug, 'product_cat' );
2192
2193 //echo "termo Id";
2194 //var_dump($productCategory->term_id);
2195 if($productCategory){
2196 $cat_id = get_term_by('id',$productCategory->term_id , 'product_cat' );
2197 }else{
2198 return false;
2199 }
2200 //$cat_id = get_category($productCategory->term_id);
2201 //echo "cat_id";
2202 //var_dump($cat_id);
2203 }
2204
2205 if(empty($cat_id)) {
2206 //echo "insere um termo se não existir a categoria<br>";
2207 //var_dump($cat_id);
2208 $arg = array( 'description' => $slug, 'parent' => 0 );
2209 $cat_id = wp_insert_term($slug, "product_cat", $arg);
2210 //echo "id inserido da categoria criada<br>";
2211 //var_dump($cat_id);
2212 return $cat_id['term_id'];
2213 }else{
2214 //var_dump("retornando resultado existindo uma categoria correspondente");
2215 return $cat_id->term_id;
2216 }
2217}
2218/**
2219 * Update a new variable product (with new attributes if they are).
2220 * (Needed functions:
2221 *
2222 * @since 3.0.0
2223 * @param array $data | The data to insert in the product.
2224 */
2225function update_product_variation($data){
2226 if( ! function_exists ('save_product_attribute_from_name') ) return;
2227
2228 $category_id = get_product_category($data['category']);
2229 $postname = sanitize_title( $data['title'] );
2230 $author = empty( $data['author'] ) ? '1' : $data['author'];
2231
2232 if(empty($data['excerpt'])){
2233 $data['excerpt'] = $postname;
2234 }
2235
2236
2237 if(empty($data['ID'])){
2238
2239 $post_data = array(
2240 'post_author' => $author,
2241 'post_name' => $postname,
2242 'post_title' => $data['title'],
2243 'post_content' => $data['content'],
2244 'post_excerpt' => $data['excerpt'],
2245 'post_status' => 'publish',
2246 'ping_status' => 'closed',
2247 'post_type' => 'product',
2248 'guid' => home_url( '/product/'.$postname.'/') ,
2249 'tax_input' => ['product_cat' => $category_id]
2250 );
2251
2252 $product_id = wp_insert_post( $post_data );
2253 //wp_set_post_terms($product_id, get_term()->slug,'product_cat',true);
2254 }else{
2255
2256 if(!$data['insert_variable_product_unique']){
2257 $post_data = array(
2258 'ID' => $data['ID'],
2259 'post_author' => $author,
2260 'post_name' => $postname,
2261 'post_title' => $data['title'],
2262 'post_content' => $data['content'],
2263 'post_excerpt' => $data['excerpt'],
2264 'post_status' => 'publish',
2265 'ping_status' => 'closed',
2266 'post_type' => 'product',
2267 'guid' => home_url( '/product/'.$postname.'/' ),
2268 'tax_input' => ['product_cat'=>$category_id]
2269 );
2270 $product_id = wp_update_post( $post_data );
2271 }
2272
2273 }
2274
2275 $product = new WC_Product_Variable( $product_id );
2276 $product->save();
2277
2278 ## ---------------------- Other optional data ---------------------- ##
2279 ## (see WC_Product and WC_Product_Variable setters methods)
2280
2281 //THE PRICES (No prices yet as we need to create product variations)
2282 //IMAGES GALLERY
2283 if( ! empty( $data['gallery_ids'] ) && count( $data['gallery_ids'] ) > 0 )
2284 $product->set_gallery_image_ids( $data['gallery_ids'] );
2285
2286 //SKU
2287 if( ! empty( $data['sku'] ) )
2288 $product->set_sku( $data['sku'] );
2289
2290 // STOCK (stock will be managed in variations)
2291 $product->set_stock_quantity( $data['stock'] ); // Set a minimal stock quantity
2292 if($data['manager_stock'] == '0'){
2293 $product->set_manage_stock(false);
2294 }else{
2295 $product->set_manage_stock(true);
2296 }
2297
2298 $product->set_stock_status('');
2299
2300 // Tax class
2301 if( empty( $data['tax_class'] ) )
2302 $product->set_tax_class( $data['tax_class'] );
2303
2304 // WEIGHT
2305 if( ! empty($data['weight']) )
2306 $product->set_weight(''); // weight (reseting)
2307 else
2308 $product->set_weight($data['weight']);
2309
2310 //length
2311 if( ! empty($data['length']) )
2312 $product->set_length(''); // length (reseting)
2313 else
2314 $product->set_length($data['length']);
2315
2316 $product->validate_props(); // Check validation
2317
2318 //WIDTH
2319 if( ! empty($data['width']) )
2320 $product->set_width(""); // weight (reseting)
2321else
2322 $product->set_width($data['width']);
2323
2324 ## ---------------------- VARIATION ATTRIBUTES ---------------------- ##
2325
2326 $product_attributes = array();
2327 //var_dump($product);
2328 var_dump($data['attributes']);
2329 foreach( $data['attributes'] as $key => $terms ){
2330 $taxonomy = wc_attribute_taxonomy_name($key); // The taxonomy slug
2331 $attr_label = ucfirst($key); // attribute label name
2332 $attr_name = ( wc_sanitize_taxonomy_name($key)); // attribute slug
2333
2334 // NEW Attributes: Register and save them
2335 if( ! taxonomy_exists( $taxonomy ) )
2336 save_product_attribute_from_name( $attr_name, $attr_label );
2337
2338 $product_attributes[$taxonomy] = array (
2339 'name' => $taxonomy,
2340 'value' => '',
2341 'position' => '',
2342 'is_visible' => 0,
2343 'is_variation' => 1,
2344 'is_taxonomy' => 1
2345 );
2346
2347 foreach( $terms as $value ){
2348 $term_name = ucfirst($value);
2349 $term_slug = sanitize_title($value);
2350
2351 // Check if the Term name exist and if not we create it.
2352 if( ! term_exists( $value, $taxonomy ) )
2353 wp_insert_term( $term_name, $taxonomy, array('slug' => $term_slug ) ); // Create the term
2354
2355 // Set attribute values
2356 if($data['insert_variable_product_unique']){
2357 wp_set_post_terms( $data['ID'], $term_name, $taxonomy, true );
2358 }else{
2359 wp_set_post_terms( $product_id, $term_name, $taxonomy, true );
2360 }
2361
2362 }
2363 }
2364 //print_r($product);
2365 if(isset($data['insert_variable_product_unique'])){
2366 update_post_meta( $data['ID'], '_product_attributes', $product_attributes );
2367 }else{
2368 update_post_meta( $product_id, '_product_attributes', $product_attributes );
2369 }
2370 //var_dump($product);
2371 //exit;
2372 $product->save(); // Save the data
2373 return $product_id;
2374}
2375/*
2376*
2377$parent_id = 746; // Or get the variable product id dynamically
2378
2379// The variation data
2380$variation_data = array(
2381 'attributes' => array(
2382 'size' => 'M',
2383 'color' => 'Green',
2384 ),
2385 'sku' => '',
2386 'regular_price' => '22.00',
2387 'sale_price' => '',
2388 'stock_qty' => 10,
2389);
2390
2391// The function to be run
2392create_product_variation( $parent_id, $variation_data );
2393*/
2394/**
2395 * Create a product variation for a defined variable product ID.
2396 *
2397 * @since 3.0.0
2398 * @param int $product_id | Post ID of the product parent variable product.
2399 * @param array $variation_data | The data to insert in the product.
2400 */
2401
2402function _create_product_variation( $product_id, $variation_data ){
2403 // Get the Variable product object (parent)
2404 $product = wc_get_product($product_id);
2405
2406 // Creating the product variation
2407 if(empty($variation_data['update'])){
2408 //var_dump($variation_data);
2409 $variation_post = array(
2410 'post_title' => MigrationRules::getProductTeste()->produtoNome,
2411 'post_name' => 'product-'. MigrationRules::getPostId() .'-variation',
2412 'post_status' => 'publish',
2413 'post_parent' => MigrationRules::getPostId(),
2414 'post_type' => 'product_variation',
2415 'guid' => site_url() . "/" . MigrationRules::getPostId()
2416 );
2417
2418 $variation_id = wp_insert_post( $variation_post );
2419 }else{
2420
2421 $variation_post = array(
2422 'ID' => $variation_data['ID'],
2423 'post_title' => $product->get_name(),
2424 'post_name' => 'product-'.$product_id.'-variation',
2425 'post_status' => 'publish',
2426 'post_parent' => $product_id,
2427 'post_type' => 'product_variation',
2428 'guid' => $product->get_permalink()
2429 );
2430
2431 $variation_id = wp_update_post( $variation_post );
2432 }
2433
2434
2435
2436 // Get an instance of the WC_Product_Variation object
2437 $variation = new WC_Product_Variation( $variation_id );
2438 //var_dump($variation_id);
2439 //exit;
2440
2441 foreach ($variation_data['attributes'] as $attribute => $term_name )
2442 {
2443 $taxonomy = 'pa_'.$attribute; // The attribute taxonomy
2444
2445 // If taxonomy doesn't exists we create it (Thanks to Carl F. Corneil)
2446 if( ! taxonomy_exists( $taxonomy ) ){
2447 register_taxonomy(
2448 $taxonomy,
2449 'product_variation',
2450 array(
2451 'hierarchical' => false,
2452 'label' => ucfirst( $attribute ),
2453 'query_var' => true,
2454 'rewrite' => array( 'slug' => sanitize_title($attribute) ), // The base slug
2455 )
2456 );
2457 }
2458
2459 // Check if the Term name exist and if not we create it.
2460 if( ! term_exists( $term_name, $taxonomy ) )
2461 wp_insert_term( $term_name, $taxonomy ); // Create the term
2462
2463 $term_slug = get_term_by('name', $term_name, $taxonomy )->slug; // Get the term slug
2464
2465 // Get the post Terms names from the parent variable product.
2466 $post_term_names = wp_get_post_terms( $product_id, $taxonomy, array('fields' => 'names') );
2467
2468 // Check if the post term exist and if not we set it in the parent variable product.
2469 if( ! in_array( $term_name, $post_term_names ) )
2470 wp_set_post_terms( $product_id, $term_name, $taxonomy, true );
2471
2472 // Set/save the attribute data in the product variation
2473 update_post_meta( $variation_id, 'attribute_'.$taxonomy, $term_slug, true);
2474 }
2475
2476 ## Set/save all other data
2477
2478
2479 // SKU
2480 //if( ! empty( $variation_data['sku'] ) )
2481 // $variation->set_sku( $variation_data['sku'] );
2482
2483 // Prices
2484 if( empty( $variation_data['sale_price'] ) ){
2485 $variation->set_price( $variation_data['regular_price'] );
2486 } else {
2487 $variation->set_price( $variation_data['sale_price'] );
2488 $variation->set_sale_price( $variation_data['sale_price'] );
2489 }
2490 $variation->set_regular_price( $variation_data['regular_price'] );
2491
2492 // Stock
2493 var_dump($variation_data['stock_qty']);
2494 if( ! empty($variation_data['stock_qty']) ){
2495 $variation->set_stock_quantity( $variation_data['stock_qty'] );
2496 $variation->set_manage_stock(true);
2497 $variation->set_stock_status('');
2498 } else {
2499 $variation->set_manage_stock(true);
2500 }
2501
2502 $variation->set_weight(''); // weight (reseting)
2503 //var_dump( $variation_data['ID']);
2504 $variation->save(); // Save the data
2505 //var_dump($variation->get_stock_quantity());
2506 //exit;
2507}
2508
2509function tirarAcentos($string){
2510 return preg_replace(array("/(á|à|ã|â|ä)/","/(Á|À|Ã|Â|Ä)/","/(é|è|ê|ë)/","/(É|È|Ê|Ë)/","/(í|ì|î|ï)/","/(Í|Ì|Î|Ï)/","/(ó|ò|õ|ô|ö)/","/(Ó|Ò|Õ|Ô|Ö)/","/(ú|ù|û|ü)/","/(Ú|Ù|Û|Ü)/","/(ñ)/","/(Ñ)/"),explode(" ","a A e E i I o O u U n N"),$string);
2511}
2512
2513/**
2514 * Method to delete Woo Product
2515 *
2516 * @param int $id the product ID.
2517 * @param bool $force true to permanently delete product, false to move to trash.
2518 * @return \WP_Error|boolean
2519 */
2520function wh_deleteProduct($id, $force = FALSE)
2521{
2522 $product = wc_get_product($id);
2523
2524 if(empty($product))
2525 return new WP_Error(999, sprintf(__('No %s is associated with #%d', 'woocommerce'), 'product', $id));
2526
2527 // If we're forcing, then delete permanently.
2528 if ($force)
2529 {
2530 if ($product->is_type('variable'))
2531 {
2532 foreach ($product->get_children() as $child_id)
2533 {
2534 $child = wc_get_product($child_id);
2535 $child->delete(true);
2536 }
2537 }
2538 elseif ($product->is_type('grouped'))
2539 {
2540 foreach ($product->get_children() as $child_id)
2541 {
2542 $child = wc_get_product($child_id);
2543 $child->set_parent_id(0);
2544 $child->save();
2545 }
2546 }
2547
2548 $product->delete(true);
2549 $result = $product->get_id() > 0 ? false : true;
2550 }
2551 else
2552 {
2553 $product->delete();
2554 $result = 'trash' === $product->get_status();
2555 }
2556
2557 if (!$result)
2558 {
2559 return new WP_Error(999, sprintf(__('This %s cannot be deleted', 'woocommerce'), 'product'));
2560 }
2561
2562 // Delete parent product transients.
2563 if ($parent_id = wp_get_post_parent_id($id))
2564 {
2565 wc_delete_product_transients($parent_id);
2566 }
2567 return true;
2568}
2569
2570/**
2571 * Add a widget to the dashboard.
2572 *
2573 * This function is hooked into the 'wp_dashboard_setup' action below.
2574 */
2575function wporg_add_dashboard_widgets() {
2576 wp_add_dashboard_widget(
2577 'wporg_dashboard_widget', // Widget slug.
2578 esc_html__( 'Wiki Importer', 'wporg' ), // Title.
2579 'wporg_dashboard_widget_render' // Display function.
2580 );
2581}
2582add_action( 'wp_dashboard_setup', 'wporg_add_dashboard_widgets' );
2583
2584/**
2585 * Create the function to output the content of our Dashboard Widget.
2586 */
2587function wporg_dashboard_widget_render() {
2588 // Display whatever you want to show.
2589 $html = '<h2>Clique <a href="admin.php?action=executeWikiImport">aqui</a> para importar Dados do ERP Wiki</h2>
2590 <img src="https://img2.pngio.com/data-import-microbiz-cloud-pos-import-data-png-537_368.png"/>';
2591 echo $html;
2592}
2593
2594add_action( 'importInitializer', 'executeWikiImport', 20,0);
2595do_action('importInitializer');
2596
2597function executeWikiImport(){
2598 if(isset($_GET['action']) && $_GET['action']=="executeWikiImport"){
2599 //initMigration();
2600 //initMigration();
2601 //create curl resource
2602 $ch = curl_init();
2603 curl_setopt($ch, CURLOPT_URL, "http://localhost/favelachick/checkout/order-received/19606/?key=wc_order_1TMRfz22JXnYf");
2604 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
2605 $output = curl_exec($ch);
2606 curl_close($ch);
2607 }
2608}
2609
2610
2611//add_action( 'woocommerce_thankyou', 'MyPersistRemoteObject3', 20, 2 );
2612function MyPersistRemoteObject3($order_id){
2613
2614 $ch = curl_init();
2615 curl_setopt_array($ch, array(
2616 CURLOPT_URL => "http://localhost/favelachick/wp-json/wc/v3/orders/" . $order_id . "/?consumer_key=ck_9e747cfe973b52e14180a7c0c84aac41c8e960ec&consumer_secret=cs_225e4823dd0664b95f6030600dfebf8209ded416",
2617 CURLOPT_RETURNTRANSFER => true,
2618 CURLOPT_ENCODING => "",
2619 CURLOPT_MAXREDIRS => 10,
2620 CURLOPT_TIMEOUT => 30,
2621 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
2622 CURLOPT_CUSTOMREQUEST => "GET",
2623 CURLOPT_SSL_VERIFYPEER=> false,
2624
2625 CURLOPT_HTTPHEADER => array(
2626 "Authorization: Basic *****************",
2627 "Cache-Control: no-cache"
2628 ),
2629 ));
2630
2631 $result = curl_exec($ch);
2632
2633 $replaced_result = substr_replace($result, '"empresa":392, "guid":"4c6e6dab-6d6d-43d9-8f71-7f12158f8f85",', 12,0);
2634
2635 //print_r($replaced_result);
2636 //echo " ";
2637 //print_r(base64_encode($replaced_result));
2638 $opts = [
2639 'http' => [
2640 'method' => 'GET'
2641 ]
2642 ];
2643
2644 $context = stream_context_create($opts);
2645 $result = file_get_contents('http://app.wikisistemas.com.br:8086/EcommerceExternoWebservice.asmx/RecebePedidoWooCommerce?json=' . base64_encode($replaced_result), false, $context);
2646 var_dump($result);
2647
2648 }
2649