public static function update_orders_value( $post_id, $post ) {
		if ( is_int( wp_is_post_revision( $post_id ) ) ) return;
		if ( is_int( wp_is_post_autosave( $post_id ) ) ) return;
		if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return $post_id;
		if ( ! current_user_can( 'edit_post', $post_id ) ) return $post_id;
		if ( $post->post_type != 'product' ) return $post_id;
		
		if ( version_compare( WC()->version, '2.2.0', '<' ) ) {
			$product 	= get_product( $post );
		} else {
			$product 	= wc_get_product( $post );
		}
		if ( $product ) {
			if ( $product->is_on_sale() ) {
				update_post_meta( $post_id, '_psad_onsale_order', 2 );
			} else {
				update_post_meta( $post_id, '_psad_onsale_order', 1 );
			}
			if ( $product->is_featured() ) {
				update_post_meta( $post_id, '_psad_featured_order', 2 );
			} else {
				update_post_meta( $post_id, '_psad_featured_order', 1 );	
			}
		}
	}
 public function add_est_simple_field($post_id)
 {
     global $post, $thepostid, $product;
     $thepostid = $post->ID;
     $product = wc_get_product($thepostid);
     $get_value = 'eddwc_get_';
     $get_value .= $product->get_type();
     echo '<div class="options_group show_if_simple hide_if_external show_if_variable">';
     $type = eddwc_option('display_type');
     $field_type = 'number';
     $fieldClass = '';
     $custom_attributes = '';
     $value = $get_value($thepostid);
     if ($type == 'general_date') {
         $field_type = 'hidden';
         $custom_attributes = array('date-type' => 'range_select');
     } else {
         if ($value != '') {
             $value = explode(',', $value);
             if (isset($value[0]) && isset($value[1]) && $value[0] > $value[1]) {
                 $value = $value[0];
             } else {
                 if (isset($value[0]) && !isset($value[1])) {
                     $value = $value[0];
                 } else {
                     $value = $value[1];
                 }
             }
         }
     }
     woocommerce_wp_text_input(array('id' => EDDWCP_METAKEY, 'label' => __('Est. Dispatch Date:', EDDWC_TXT), 'placeholder' => __('number', EDDWC_TXT), 'type' => $field_type, 'wrapper_class' => $fieldClass, 'value' => $value, 'custom_attributes' => $custom_attributes));
     echo '</div>';
 }
    public static function output()
    {
        global $post, $thepostid;
        $thepostid = $post->ID;
        $_product = wc_get_product($thepostid);
        $terms = array();
        $delivery_time = $_product->gzd_product->delivery_time;
        woocommerce_wp_select(array('id' => '_unit', 'label' => __('Unit', 'woocommerce-germanized'), 'options' => array_merge(array('none' => __('Select unit', 'woocommerce-germanized')), WC_germanized()->units->get_units()), 'desc_tip' => true, 'description' => __('Needed if selling on a per unit basis', 'woocommerce-germanized')));
        woocommerce_wp_text_input(array('id' => '_unit_base', 'label' => __('Unit Base', 'woocommerce-germanized'), 'data_type' => 'decimal', 'desc_tip' => true, 'description' => __('Unit price per amount (e.g. 100)', 'woocommerce-germanized')));
        woocommerce_wp_text_input(array('id' => '_unit_price_regular', 'label' => __('Regular Unit Price', 'woocommerce-germanized') . ' (' . get_woocommerce_currency_symbol() . ')', 'data_type' => 'price'));
        woocommerce_wp_text_input(array('id' => '_unit_price_sale', 'label' => __('Sale Unit Price', 'woocommerce-germanized') . ' (' . get_woocommerce_currency_symbol() . ')', 'data_type' => 'price'));
        if (version_compare(WC()->version, '2.3', '<')) {
            return;
        }
        ?>
		
		<p class="form-field">
			<label for="delivery_time"><?php 
        _e('Delivery Time', 'woocommerce-germanized');
        ?>
</label>
			<input type="hidden" class="wc-product-search wc-gzd-delivery-time-search" style="width: 50%" id="delivery_time" name="delivery_time" data-minimum_input_length="1" data-allow_clear="true" data-placeholder="<?php 
        _e('Search for a delivery time&hellip;', 'woocommerce-germanized');
        ?>
" data-action="woocommerce_gzd_json_search_delivery_time" data-multiple="false" data-selected="<?php 
        echo $delivery_time ? $delivery_time->name : '';
        ?>
" value="<?php 
        echo $delivery_time ? $delivery_time->term_id : '';
        ?>
" />
		</p>
		
		<?php 
    }
 /**
  * Add order item via ajax
  * exact copy from /wp-content/plugins/woocommerce/includes/class-wc-ajax.php, with change to template selection
  */
 public static function add_order_item()
 {
     check_ajax_referer('order-item', 'security');
     $item_to_add = sanitize_text_field($_POST['item_to_add']);
     $order_id = absint($_POST['order_id']);
     // Find the item
     if (!is_numeric($item_to_add)) {
         die;
     }
     $post = get_post($item_to_add);
     if (!$post || 'product' !== $post->post_type && 'product_variation' !== $post->post_type) {
         die;
     }
     $_product = wc_get_product($post->ID);
     $order = wc_get_order($order_id);
     $order_taxes = $order->get_taxes();
     $class = 'new_row';
     // Set values
     $item = array();
     $item['product_id'] = $_product->id;
     $item['variation_id'] = isset($_product->variation_id) ? $_product->variation_id : '';
     $item['variation_data'] = isset($_product->variation_data) ? $_product->variation_data : '';
     $item['name'] = $_product->get_title();
     $item['tax_class'] = $_product->get_tax_class();
     $item['qty'] = 1;
     $item['line_subtotal'] = wc_format_decimal($_product->get_price_excluding_tax());
     $item['line_subtotal_tax'] = '';
     $item['line_total'] = wc_format_decimal($_product->get_price_excluding_tax());
     $item['line_tax'] = '';
     // Add line item
     $item_id = wc_add_order_item($order_id, array('order_item_name' => $item['name'], 'order_item_type' => 'line_item'));
     // Add line item meta
     if ($item_id) {
         wc_add_order_item_meta($item_id, '_qty', $item['qty']);
         wc_add_order_item_meta($item_id, '_tax_class', $item['tax_class']);
         wc_add_order_item_meta($item_id, '_product_id', $item['product_id']);
         wc_add_order_item_meta($item_id, '_variation_id', $item['variation_id']);
         wc_add_order_item_meta($item_id, '_line_subtotal', $item['line_subtotal']);
         wc_add_order_item_meta($item_id, '_line_subtotal_tax', $item['line_subtotal_tax']);
         wc_add_order_item_meta($item_id, '_line_total', $item['line_total']);
         wc_add_order_item_meta($item_id, '_line_tax', $item['line_tax']);
         // Since 2.2
         wc_add_order_item_meta($item_id, '_line_tax_data', array('total' => array(), 'subtotal' => array()));
         // Store variation data in meta
         if ($item['variation_data'] && is_array($item['variation_data'])) {
             foreach ($item['variation_data'] as $key => $value) {
                 wc_add_order_item_meta($item_id, str_replace('attribute_', '', $key), $value);
             }
         }
         do_action('woocommerce_ajax_add_order_item_meta', $item_id, $item);
     }
     $item = apply_filters('woocommerce_ajax_order_item', $item, $item_id);
     //include( 'admin/meta-boxes/views/html-order-item.php' );
     //@@@@LOUSHOU - allow overtake of template
     include apply_filters('qsot-woo-template', 'meta-boxes/views/html-order-item.php', 'admin');
     // Quit out
     die;
 }
 /**
  * Get settings array
  *
  * @return array
  */
 public function get_settings()
 {
     $values = WC_Order_Simulator::get_settings();
     // selected products
     $product_ids = array_filter(array_map('absint', $values['products']));
     $json_ids = array();
     foreach ($product_ids as $product_id) {
         $product = wc_get_product($product_id);
         if (is_object($product)) {
             $json_ids[$product_id] = wp_kses_post(html_entity_decode($product->get_formatted_name(), ENT_QUOTES, get_bloginfo('charset')));
         }
     }
     $data_selected = esc_attr(json_encode($json_ids));
     $data_value = implode(',', array_keys($json_ids));
     $next_scheduled = wp_next_scheduled('wcos_create_orders');
     if (!$next_scheduled) {
         $message = 'Schedule not found. Please deactivate then activate the plugin to fix the scheduler.';
     } else {
         $format = get_option('date_format') . ' ' . get_option('time_format');
         $now = date($format, current_time('timestamp', true));
         $message = 'Current time: <code>' . $now . ' GMT</code><br/>Next run: <code>' . date(get_option('date_format') . ' ' . get_option('time_format'), $next_scheduled) . ' GMT</code>';
     }
     $settings = apply_filters('woocommerce_order_simulator_settings', array(array('title' => __('Settings', 'woocommerce'), 'type' => 'title', 'desc' => $message, 'id' => 'wcos_settings'), array('title' => __('Orders per Hour', 'woocommerce'), 'desc' => __('The maximum number of orders to generate per hour.', 'woocommerce'), 'id' => 'wcos_orders_per_hour', 'css' => 'width:100px;', 'default' => $values['orders_per_hour'], 'type' => 'number', 'desc_tip' => true), array('title' => __('Products', 'woocommerce'), 'desc' => __('The products that will be added to the generated orders. Leave empty to randomly select from all products.', 'woocommerce'), 'id' => 'wcos_products', 'default' => $data_value, 'type' => 'text', 'class' => 'wc-product-search', 'css' => 'min-width: 350px;', 'custom_attributes' => array('data-multiple' => "true", 'data-selected' => $data_selected), 'desc_tip' => true), array('title' => __('Min Order Products', 'woocommerce'), 'id' => 'wcos_min_order_products', 'desc' => __('The minimum number of products to add to the generated orders', 'woocommerce'), 'type' => 'number', 'custom_attributes' => array('min' => 1), 'default' => $values['min_order_products'], 'css' => 'width:50px;', 'autoload' => false), array('title' => __('Max Order Products', 'woocommerce'), 'desc' => '', 'id' => 'wcos_max_order_products', 'desc' => __('The maximum number of products to add to the generated orders', 'woocommerce'), 'type' => 'number', 'custom_attributes' => array('min' => 1), 'default' => $values['max_order_products'], 'css' => 'width:50px;', 'autoload' => false), array('title' => __('Create User Accounts', 'woocommerce'), 'desc_tip' => true, 'id' => 'wcos_create_users', 'desc' => __('If enabled, accounts will be created and will randomly assigned to new orders.', 'woocommerce'), 'type' => 'select', 'options' => array(0 => __('No - assign existing accounts to new orders', 'woocommerce'), 1 => __('Yes - create a new account or randomly select an existing account to assign to new orders', 'woocommerce')), 'default' => $values['create_users'], 'autoload' => false, 'class' => 'wc-enhanced-select'), array('title' => __('Completed Order Status Chance', 'woocommerce'), 'desc_tip' => false, 'id' => 'wcos_order_completed_pct', 'desc' => __('%', 'woocommerce'), 'type' => 'number', 'default' => $values['order_completed_pct'], 'autoload' => false, 'css' => 'width:50px;', 'custom_attributes' => array('min' => 0, 'max' => 100)), array('title' => __('Processing Order Status Chance', 'woocommerce'), 'desc_tip' => false, 'id' => 'wcos_order_processing_pct', 'desc' => __('%', 'woocommerce'), 'type' => 'number', 'default' => $values['order_processing_pct'], 'autoload' => false, 'css' => 'width:50px;', 'custom_attributes' => array('min' => 0, 'max' => 100)), array('title' => __('Failed Order Status Chance', 'woocommerce'), 'desc_tip' => false, 'id' => 'wcos_order_failed_pct', 'desc' => __('%', 'woocommerce'), 'type' => 'number', 'default' => $values['order_failed_pct'], 'autoload' => false, 'css' => 'width:50px;', 'custom_attributes' => array('min' => 0, 'max' => 100)), array('type' => 'sectionend', 'id' => 'wcos_settings')));
     return apply_filters('woocommerce_get_settings_' . $this->id, $settings);
 }
 public function gather_products_data(&$products_info)
 {
     //return array();
     $args = array('post_type' => 'product', 'posts_per_page' => -1);
     $loop = new WP_Query($args);
     if ($loop->have_posts()) {
         while ($loop->have_posts()) {
             $loop->the_post();
             $the_ID = get_the_ID();
             //$the_product = new WC_Product( $the_ID );
             $the_product = wc_get_product($the_ID);
             $the_price = $the_product->get_price();
             $the_stock = $the_product->get_total_stock();
             //if ( 0 == $the_stock )
             //$the_stock = get_post_meta( $the_ID, '_stock', true );
             $the_title = get_the_title();
             $the_date = get_the_date();
             $the_permalink = get_the_permalink();
             $post_custom = get_post_custom($the_ID);
             $total_sales = isset($post_custom['total_sales'][0]) ? $post_custom['total_sales'][0] : 0;
             //$available_variations = $the_product->get_available_variations();
             $purchase_price = wc_get_product_purchase_price($the_ID);
             $sales_in_day_range = array();
             foreach ($this->ranges_in_days as $the_range) {
                 $sales_in_day_range[$the_range] = 0;
             }
             $products_info[$the_ID] = array('ID' => $the_ID, 'title' => $the_title, 'permalink' => $the_permalink, 'price' => $the_price, 'stock' => $the_stock, 'stock_price' => $the_price * $the_stock, 'total_sales' => $total_sales, 'date_added' => $the_date, 'purchase_price' => $purchase_price, 'last_sale' => 0, 'sales_in_period' => $sales_in_day_range);
         }
     }
 }
/**
 * Checks if a given product is of a switchable type
 *
 * @param int|WC_Product $product A WC_Product object or the ID of a product to check
 * @return bool
 * @since  2.0
 */
function wcs_is_product_switchable_type($product)
{
    if (!is_object($product)) {
        $product = wc_get_product($product);
    }
    $variation = null;
    if (empty($product)) {
        $is_product_switchable = false;
    } else {
        // back compat for parent products
        if ($product->is_type('subscription_variation') && !empty($product->parent)) {
            $variation = $product;
            $product = $product->parent;
        }
        $allow_switching = get_option(WC_Subscriptions_Admin::$option_prefix . '_allow_switching', 'no');
        switch ($allow_switching) {
            case 'variable':
                $is_product_switchable = $product->is_type(array('variable-subscription', 'subscription_variation')) ? true : false;
                break;
            case 'grouped':
                $is_product_switchable = 0 !== $product->post->post_parent ? true : false;
                break;
            case 'variable_grouped':
                $is_product_switchable = $product->is_type(array('variable-subscription', 'subscription_variation')) || 0 !== $product->post->post_parent ? true : false;
                break;
            case 'no':
            default:
                $is_product_switchable = false;
                break;
        }
    }
    return apply_filters('wcs_is_product_switchable', $is_product_switchable, $product, $variation);
}
Пример #8
0
/**
 * DEVUELVE EL HTML DE LOS INGREDIENTES
 */
function getHtmlIngredientes($ingredientes, $producto_id)
{
    $html = '<h2 class="[ text-center color-dark ][ no-margin--top ]">' . get_the_title($producto_id) . '</h2>';
    $html .= '<div class="[ row ]">';
    if (!empty($ingredientes)) {
        foreach ($ingredientes as $key => $ingrediente) {
            $html .= '<div class="[ col-xs-3 col-md-2 ]">';
            $html .= '<a class="[ box-content ]" href="' . site_url('/recetas/') . '?ingrediente=' . $ingrediente->ingrediente_id . '">';
            $url_img = attachment_image_url($ingrediente->ingrediente_id, 'medium');
            $html .= '<img class="[ image-responsive ]" alt="" src="' . $url_img . '">';
            $html .= '<p class="[ text-center ]">' . get_the_title($ingrediente->ingrediente_id) . '</p>';
            $html .= '</a>';
            $html .= '</div>';
        }
    }
    $html .= '</div>';
    $producto = wc_get_product($producto_id);
    $variations = $producto->get_available_variations();
    $addToCart = '';
    $costoVariationSemanal = 0;
    $costoTotal = 0;
    $html .= '<div class="[ card__radio-options ][ text-center color-dark ]">';
    $html .= '<div class="[ radio-options__label ]">';
    $html .= 'Entregas semanales durante:';
    $html .= '</div>';
    if (!empty($variations)) {
        $count = 1;
        foreach ($variations as $variation) {
            $name = getNameVariation($variation['variation_id']);
            $check = $count == 1 ? 'checked' : '';
            $nombreVariacion = getNameOriginVariation($variation['variation_id']);
            $cansatSemanal = getCostoCanastaTemporalidad($nombreVariacion, $variation['display_price']);
            if ($count == 1) {
                $addToCart = site_url('/mi-carrito/?add-to-cart=') . $variation['variation_id'];
                $costoVariationSemanal = $cansatSemanal;
                $costoTotal = $variation['display_price'];
            }
            $html .= '<label class="[ radio-options__selector__label ]" for="c9_meals-' . $variation['variation_id'] . '">';
            $html .= '<input ';
            $html .= 'id="c9_meals-' . $variation['variation_id'] . '"';
            $html .= 'data-costo="' . number_format($variation['display_price']) . '"';
            $html .= 'data-producto="' . $producto_id . '"';
            $html .= 'data-variacion="' . $variation['variation_id'] . '"';
            $html .= 'data-semanal="' . $cansatSemanal . '"';
            $html .= 'class="[ radio-options__selector ][ check-compra-modal ]" ';
            $html .= 'type="radio"';
            $html .= 'name="variaciones-00' . $producto_id . '"';
            $html .= 'value="c9"';
            $html .= $check;
            $html .= '>' . $name;
            $html .= '</label>';
            $count++;
        }
    }
    $html .= '</div>';
    $html .= '<div class="text-center">';
    $html .= '<a class="[ btn btn-secondary ] url-add-cart-product-modal-00' . $producto_id . '" href="' . $addToCart . '">Añadir al carrito</a>';
    $html .= '</div>';
    return $html;
}
 /**
  * @param $product_id
  * @param $downloads
  * @return $files (all product downloads)
  */
 static function post_downloads($product_id, $downloads)
 {
     // $filename should be the path to a file in the upload directory.
     // example $filename = 'woocommerce_uploads/2015/07/aka_Matrix42_Tool_CleanDatabase_7.2.1.20150625.aka.zip';
     $downloads = json_decode($downloads);
     // Get all existing post downloads and add the new passed downloads
     $files = array();
     $result_all_files = array();
     $wc_product = wc_get_product($product_id);
     $untyped_array_of_downloads = $wc_product->get_files();
     foreach ($untyped_array_of_downloads as $download_key => $download_value) {
         // Add existing download to the $files array
         $existing_download = (object) $download_value;
         $files[md5($existing_download->file)] = array('name' => $existing_download->name, 'file' => $existing_download->file);
     }
     foreach ($downloads as $key => $new_download) {
         // Add the new downloads to the existing post downloads
         $files[md5($new_download->file)] = array('name' => $new_download->name, 'file' => $new_download->file);
     }
     // Update product post meta (_downloadable_files)
     update_post_meta($product_id, '_downloadable_files', $files);
     // Collect downloads just for function result
     foreach ($files as $key => $download) {
         array_push($result_all_files, $download);
     }
     return $result_all_files;
 }
Пример #10
0
function wdm_add_custom_settings()
{
    global $woocommerce, $post;
    print_r(wc_get_product($post));
    echo '<script>
    jQuery(document).ready(function($) {
        $("#datepicker").datepicker();
    });
</script>';
    echo ' <div class="options_group show_if_willow_prod_2"><div id="datepicker"></div>
    <input type="hidden" name="tipo" value="pre-produto">';
    // Create a number field, for example for UPC
    // woocommerce_wp_text_input(
    //   array(
    //    'id'                => 'dias_envio',
    //    'label'             => __( 'Dias para o envio', 'woocommerce' ),
    //    'placeholder'       => '',
    //    'desc_tip'    => 'true',
    //    'description'       => __( 'Digite o numero de dias ', 'woocommerce' ),
    //    'type'              => 'number'
    //    ));
    // // Create a checkbox for product purchase status
    //   woocommerce_wp_checkbox(
    //    array(
    //    'id'            => 'wdm_is_purchasable',
    //    'label'         => __('Is Purchasable', 'woocommerce' )
    //    ));
    echo '</div>';
}
 static function post_attachment($download, $product_id)
 {
     // $filename should be the path to a file in the upload directory.
     // example $filename = 'woocommerce_uploads/2015/07/aka_Matrix42_Tool_CleanDatabase_7.2.1.20150625.aka.zip';
     $download = json_decode($download);
     $filename = $download->file;
     $web_url = $download->web_url;
     $wp_upload_dir = wp_upload_dir();
     $file = $wp_upload_dir['path'] . '/' . $filename;
     //Check the type of file. We'll use this as the 'post_mime_type'.
     $filetype = wp_check_filetype(basename($file), null);
     $attachment = array('guid' => $wp_upload_dir['url'] . '/' . basename($file), 'post_mime_type' => $filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($file)), 'post_content' => '', 'post_status' => 'inherit');
     // Insert the attachment.
     $attach_id = wp_insert_attachment($attachment, $file, $product_id);
     // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
     require_once ABSPATH . 'wp-admin/includes/image.php';
     // Generate the metadata for the attachment, and update the database record.
     $attach_data = wp_generate_attachment_metadata($attach_id, $file);
     wp_update_attachment_metadata($attach_id, $attach_data);
     // Get all existing post downloads and
     $files = array();
     $wc_product = wc_get_product($product_id);
     $untyped_array_of_downloads = $wc_product->get_files();
     foreach ($untyped_array_of_downloads as $download_key => $download_value) {
         $download_name = $download_value['name'];
         $download_url = $download_value['file'];
         $files[md5($download_url)] = array('name' => $download_name, 'file' => $download_url);
     }
     // Extend the existing post downloads by the new one
     $files[md5($download_url)] = array('name' => $filename, 'file' => $web_url);
     // Update post meta (_downloadable_files)
     update_post_meta($product_id, '_downloadable_files', $files);
     return 1;
 }
    /**
     * column_default function.
     *
     * @access public
     * @param mixed $post
     * @param mixed $column_name
     */
    public function column_default($item, $column_name)
    {
        global $wpdb;
        switch ($column_name) {
            case 'product_id':
                $product = wc_get_product($item->product_id);
                return $product ? '<a href="' . admin_url('post.php?post=' . absint($product->id) . '&action=edit') . '">' . esc_html($product->get_title()) . '</a>' : __('n/a', 'wp-job-manager-wc-paid-listings');
            case 'user_id':
                $user = get_user_by('id', $item->user_id);
                if ($item->user_id && $user) {
                    return '<a href="' . admin_url('user-edit.php?user_id=' . absint($item->user_id)) . '">' . esc_attr($user->display_name) . '</a><br/><span class="description">' . esc_html($user->user_email) . '</span>';
                } else {
                    return __('n/a', 'wp-job-manager-wc-paid-listings');
                }
            case 'order_id':
                return $item->order_id > 0 ? '<a href="' . admin_url('post.php?post=' . absint($item->order_id) . '&action=edit') . '">#' . absint($item->order_id) . ' &rarr;</a>' : __('n/a', 'wp-job-manager-wc-paid-listings');
            case 'featured_job':
                return $item->package_featured ? '&#10004;' : '&ndash;';
            case 'duration':
                return $item->package_duration ? sprintf(__('%d Days', 'wp-job-manager-wc-paid-listings'), absint($item->package_duration)) : '&ndash;';
            case 'limit':
                return '<a href="' . esc_url(admin_url('edit.php?post_type=' . ('resume' === $item->package_type ? 'resume' : 'job_listing') . '&package=' . absint($item->id))) . '">' . ($item->package_limit ? sprintf(__('%s Posted', 'wp-job-manager-wc-paid-listings'), absint($item->package_count) . ' / ' . absint($item->package_limit)) : __('Unlimited', 'wp-job-manager-wc-paid-listings')) . '</a>';
            case 'package_type':
                return 'resume' === $item->package_type ? __('Resume Package', 'wp-job-manager-wc-paid-listings') : __('Job Package', 'wp-job-manager-wc-paid-listings');
            case 'job_actions':
                return '<div class="actions">
					<a class="button button-icon icon-edit" href="' . esc_url(add_query_arg(array('action' => 'edit', 'package_id' => $item->id), admin_url('users.php?page=wc_paid_listings_packages'))) . '">' . __('Edit', 'wp-job-manager-wc-paid-listings') . '</a>
					<a class="button button-icon icon-delete" href="' . wp_nonce_url(add_query_arg(array('action' => 'delete', 'package_id' => $item->id), admin_url('users.php?page=wc_paid_listings_packages')), 'delete', 'delete_nonce') . '">' . __('Delete', 'wp-job-manager-wc-paid-listings') . '</a></div>
				</div>';
        }
    }
 /**
  * Inits shortcode atts and properties.
  *
  * @version 2.5.4
  * @since   2.5.4
  * @param   array $atts Shortcode atts.
  * @return  array The (modified) shortcode atts.
  */
 function init_atts($atts)
 {
     // Atts
     if (0 == $atts['product_id']) {
         global $wcj_product_id_for_shortcode;
         if (0 != $wcj_product_id_for_shortcode) {
             $atts['product_id'] = $wcj_product_id_for_shortcode;
         } else {
             $atts['product_id'] = get_the_ID();
         }
         if (0 == $atts['product_id']) {
             return false;
         }
     }
     $the_post_type = get_post_type($atts['product_id']);
     if ('product' !== $the_post_type && 'product_variation' !== $the_post_type) {
         return false;
     }
     // Class properties
     $this->the_product = wc_get_product($atts['product_id']);
     if (!$this->the_product) {
         return false;
     }
     return $atts;
 }
Пример #14
0
 /**
  * set_sku_with_variable.
  */
 function set_sku_with_variable($product_id, $is_preview)
 {
     $this->set_sku($product_id, $product_id, '', $is_preview);
     // Handling variable products
     $variation_handling = apply_filters('wcj_get_option_filter', 'as_variable', get_option('wcj_sku_variations_handling', 'as_variable'));
     $product = wc_get_product($product_id);
     if ($product->is_type('variable')) {
         $variations = $product->get_available_variations();
         if ('as_variable' === $variation_handling) {
             foreach ($variations as $variation) {
                 $this->set_sku($variation['variation_id'], $product_id, '', $is_preview);
             }
         } else {
             if ('as_variation' === $variation_handling) {
                 foreach ($variations as $variation) {
                     $this->set_sku($variation['variation_id'], $variation['variation_id'], '', $is_preview);
                 }
             } else {
                 if ('as_variable_with_suffix' === $variation_handling) {
                     $variation_suffixes = 'abcdefghijklmnopqrstuvwxyz';
                     $abc = 0;
                     foreach ($variations as $variation) {
                         $this->set_sku($variation['variation_id'], $product_id, $variation_suffixes[$abc++], $is_preview);
                         if (26 == $abc) {
                             $abc = 0;
                         }
                     }
                 }
             }
         }
     }
 }
 /**
  * widget function.
  *
  * @see WP_Widget
  *
  * @param array $args
  * @param array $instance
  */
 public function widget($args, $instance)
 {
     global $comments, $comment;
     if ($this->get_cached_widget($args)) {
         return;
     }
     ob_start();
     $number = !empty($instance['number']) ? absint($instance['number']) : $this->settings['number']['std'];
     $comments = get_comments(array('number' => $number, 'status' => 'approve', 'post_status' => 'publish', 'post_type' => 'product'));
     if ($comments) {
         $this->widget_start($args, $instance);
         echo '<ul class="product_list_widget">';
         foreach ((array) $comments as $comment) {
             $_product = wc_get_product($comment->comment_post_ID);
             $rating = intval(get_comment_meta($comment->comment_ID, 'rating', true));
             $rating_html = $_product->get_rating_html($rating);
             echo '<li><a href="' . esc_url(get_comment_link($comment->comment_ID)) . '">';
             echo $_product->get_image();
             echo $_product->get_title() . '</a>';
             echo $rating_html;
             printf('<span class="reviewer">' . _x('by %1$s', 'by comment author', 'woocommerce') . '</span>', get_comment_author());
             echo '</li>';
         }
         echo '</ul>';
         $this->widget_end($args);
     }
     $content = ob_get_clean();
     echo $content;
     $this->cache_widget($args, $content);
 }
    /**
     * Displays the dropdown for the product filter
     * @return string the html dropdown element
     */
    public function restrict_by_product()
    {
        global $typenow;
        if ('shop_subscription' !== $typenow) {
            return;
        }
        $product_id = '';
        $product_string = '';
        if (!empty($_GET['_wcs_product'])) {
            $product_id = absint($_GET['_wcs_product']);
            $product_string = wc_get_product($product_id)->get_formatted_name();
        }
        ?>
		<input type="hidden" class="wc-product-search" name="_wcs_product" data-placeholder="<?php 
        esc_attr_e('Search for a product&hellip;', 'woocommerce-subscriptions');
        ?>
" data-action="woocommerce_json_search_products_and_variations" data-selected="<?php 
        echo esc_attr(strip_tags($product_string));
        ?>
" value="<?php 
        echo esc_attr($product_id);
        ?>
" data-allow_clear="true" />
		<?php 
    }
 /**
  * Triggered when an order is paid
  * @param  int $order_id
  */
 public function order_paid($order_id)
 {
     // Get the order
     $order = new WC_Order($order_id);
     if (get_post_meta($order_id, 'wc_paid_listings_packages_processed', true)) {
         return;
     }
     foreach ($order->get_items() as $item) {
         $product = wc_get_product($item['product_id']);
         if ($product->is_type(array('job_package', 'resume_package', 'job_package_subscription', 'resume_package_subscription')) && $order->customer_user) {
             // Give packages to user
             for ($i = 0; $i < $item['qty']; $i++) {
                 $user_package_id = wc_paid_listings_give_user_package($order->customer_user, $product->id, $order_id);
             }
             // Approve job or resume with new package
             if (isset($item['job_id'])) {
                 $job = get_post($item['job_id']);
                 if (in_array($job->post_status, array('pending_payment', 'expired'))) {
                     wc_paid_listings_approve_job_listing_with_package($job->ID, $order->customer_user, $user_package_id);
                 }
             } elseif (isset($item['resume_id'])) {
                 $resume = get_post($item['resume_id']);
                 if (in_array($resume->post_status, array('pending_payment', 'expired'))) {
                     wc_paid_listings_approve_resume_with_package($resume->ID, $order->customer_user, $user_package_id);
                 }
             }
         }
     }
     update_post_meta($order_id, 'wc_paid_listings_packages_processed', true);
 }
 /**
  * Get autoship price for current role
  * @param double $autoship_price
  * @param int $product_id
  */
 function wc_autoship_noni_pricing_current_role($autoship_price, $product_id, $autoship_frequency, $customer_id)
 {
     if (empty($customer_id)) {
         // User is not logged in
         return $autoship_price;
     }
     // Get current user
     $user = get_user_by('id', $customer_id);
     if (!$user->ID) {
         // User is not logged in
         return $autoship_price;
     }
     // Map product prices to roles
     // sorted from lowest price to highest price
     $prices = array('F1-0001' => array('salesrep' => 35.0), 'F1-0002' => array('salesrep' => 45.0), 'F1-0004' => array('salesrep' => 0.0), 'F1-0008' => array('salesrep' => 140.0), 'F1-0009' => array('salesrep' => 180.0), 'F1-0011' => array('salesrep' => 8.0), 'F1-0012' => array('salesrep' => 12.0), 'F1-0021' => array('salesrep' => 16.0), 'F1-0022' => array('salesrep' => 20.0));
     // Get product
     $product = wc_get_product($product_id);
     $product_sku = $product->get_sku();
     if (!isset($prices[$product_sku])) {
         // No prices set, return default
         return $autoship_price;
     }
     foreach ($prices[$product_sku] as $role => $price) {
         if (in_array($role, $user->roles)) {
             // User has role
             return $price;
         }
     }
     // Default
     return $autoship_price;
 }
Пример #19
0
/**
 * Save one product stock data 
 *
 */
function stock_manager_save_one_product_stock_data()
{
    if (current_user_can('manage_woocommerce')) {
        $product_id = sanitize_text_field($_POST['product']);
        check_ajax_referer('wsm-ajax-nonce-' . $product_id, 'secure');
        $sku = sanitize_text_field($_POST['sku']);
        $manage_stock = sanitize_text_field($_POST['manage_stock']);
        $stock_status = sanitize_text_field($_POST['stock_status']);
        $backorders = sanitize_text_field($_POST['backorders']);
        $stock = sanitize_text_field($_POST['stock']);
        $weight = sanitize_text_field($_POST['weight']);
        update_post_meta($product_id, '_sku', $sku);
        update_post_meta($product_id, '_manage_stock', $manage_stock);
        update_post_meta($product_id, '_stock_status', $stock_status);
        update_post_meta($product_id, '_backorders', $backorders);
        $_product = wc_get_product($product_id);
        //Set stock via product class
        $_product->set_stock($stock);
        if (!empty($_POST['regular_price'])) {
            $price = sanitize_text_field($_POST['regular_price']);
            if (!empty($_POST['sales_price'])) {
                $sale_price = sanitize_text_field($_POST['sales_price']);
                wsm_save_price($product_id, $price, $sale_price);
            } else {
                wsm_save_price($product_id, $price);
            }
        }
        update_post_meta($product_id, '_weight', $weight);
    }
    exit;
}
 /**
  * Check if we need to download a file and check validity.
  */
 public static function download_product()
 {
     $product_id = absint($_GET['download_file']);
     $product = wc_get_product($product_id);
     $data_store = WC_Data_Store::load('customer-download');
     if (!$product || !isset($_GET['key'], $_GET['order'])) {
         self::download_error(__('Invalid download link.', 'woocommerce'));
     }
     $download_ids = $data_store->get_downloads(array('user_email' => sanitize_email(str_replace(' ', '+', $_GET['email'])), 'order_key' => wc_clean($_GET['order']), 'product_id' => $product_id, 'download_id' => wc_clean(preg_replace('/\\s+/', ' ', $_GET['key'])), 'orderby' => 'downloads_remaining', 'order' => 'DESC', 'limit' => 1, 'return' => 'ids'));
     if (empty($download_ids)) {
         self::download_error(__('Invalid download link.', 'woocommerce'));
     }
     $download = new WC_Customer_Download(current($download_ids));
     self::check_order_is_valid($download);
     self::check_downloads_remaining($download);
     self::check_download_expiry($download);
     self::check_download_login_required($download);
     do_action('woocommerce_download_product', $download->get_user_email(), $download->get_order_key(), $download->get_product_id(), $download->get_user_id(), $download->get_download_id(), $download->get_order_id());
     $count = $download->get_download_count();
     $remaining = $download->get_downloads_remaining();
     $download->set_download_count($count++);
     $download->set_downloads_remaining($remaining--);
     $download->save();
     self::download($product->get_file_download_path($download->get_download_id()), $download->get_product_id());
 }
 /**
  * Gets shipping rates (for checkout) from the Connect for WooCommerce Server
  *
  * @param $services All settings for all services we want rates for
  * @param $package Package provided to WC_Shipping_Method::calculate_shipping()
  * @return object|WP_Error
  */
 public function get_shipping_rates($services, $package, $boxes)
 {
     // First, build the contents array
     // each item needs to specify quantity, weight, length, width and height
     $contents = array();
     foreach ($package['contents'] as $item_id => $values) {
         $product_id = absint($values['data']->id);
         $product = wc_get_product($product_id);
         if ($values['quantity'] > 0 && $product->needs_shipping()) {
             if (!$product->has_weight()) {
                 return new WP_Error('product_missing_weight', sprintf("Product ( ID: %d ) did not include a weight. Shipping rates cannot be calculated.", $product_id));
             }
             $height = 0;
             $length = 0;
             $weight = $product->get_weight();
             $width = 0;
             if ($product->has_dimensions()) {
                 $height = $product->get_height();
                 $length = $product->get_length();
                 $width = $product->get_width();
             }
             $contents[] = array('height' => $height, 'product_id' => isset($values['data']->variation_id) ? $values['data']->variation_id : $values['data']->id, 'length' => $length, 'quantity' => $values['quantity'], 'weight' => $weight, 'width' => $width);
         }
     }
     if (empty($contents)) {
         return new WP_Error('nothing_to_ship', 'No shipping rate could be calculated. No items in the package are shippable.');
     }
     // Then, make the request
     $body = array('contents' => $contents, 'destination' => $package['destination'], 'services' => $services, 'boxes' => $boxes);
     return $this->request('POST', '/shipping/rates', $body);
 }
Пример #22
0
function dd_select_colvariants_products()
{
    global $post, $woocommerce;
    $product_ids = array_filter(array_map('absint', (array) get_post_meta($post->ID, '_colvariants_ids', true)));
    ?>
  <div class="options_group">
    <p class="form-field">
      <label for="colvariants_ids"><?php 
    _e('Color Variants', 'woocommerce');
    ?>
</label>
      <input type="hidden" class="wc-product-search" style="width: 50%;" id="colvariants_ids" name="colvariants_ids" data-placeholder="<?php 
    _e('Search for a product&hellip;', 'woocommerce');
    ?>
" data-action="woocommerce_json_search_products" data-multiple="true" data-selected="<?php 
    $json_ids = array();
    foreach ($product_ids as $product_id) {
        $product = wc_get_product($product_id);
        if (is_object($product)) {
            $json_ids[$product_id] = wp_kses_post(html_entity_decode($product->get_formatted_name(), ENT_QUOTES, get_bloginfo('charset')));
        }
    }
    echo esc_attr(json_encode($json_ids));
    ?>
" value="<?php 
    echo implode(',', array_keys($json_ids));
    ?>
" /> <?php 
    echo wc_help_tip(__('Color variants are products which are diplayed and linked on product page as a color selector field. Please included current color variant also.', 'dd'));
    ?>
    </p>
  </div>
  <?php 
}
 /**
  * Register the stylesheets for the public-facing side of the site.
  *
  * @since    1.0.0
  */
 public function enqueue_scripts()
 {
     global $post, $product;
     if (is_object($post) && class_exists('WooCommerce')) {
         $is_product_type_variable = 'false';
         if (function_exists('wc_get_product')) {
             $product = wc_get_product($post);
             if ($product) {
                 if ($product->is_type('variable') && is_single()) {
                     $is_product_type_variable = 'true';
                 }
             }
         }
         $attach_id = isset($_SESSION['attach_id']) && !empty($_SESSION['attach_id']) ? $_SESSION['attach_id'] : '';
         if (!empty($attach_id)) {
             $total_word = get_post_meta($attach_id, 'total_word', true);
         } else {
             $total_word = '';
         }
         if (!empty($attach_id)) {
             $total_character = get_post_meta($attach_id, 'total_character', true);
         } else {
             $total_character = '';
         }
         wp_enqueue_script($this->plugin_name, plugin_dir_url(__FILE__) . 'js/woocommerce-price-per-word-public.js', array('jquery'), $this->version, false);
         if (wp_script_is($this->plugin_name)) {
             wp_localize_script($this->plugin_name, 'woocommerce_price_per_word_params', apply_filters('woocommerce_price_per_word_params', array('ajax_url' => admin_url('admin-ajax.php'), 'woocommerce_price_per_word_params_nonce' => wp_create_nonce("woocommerce_price_per_word_params_nonce"), 'total_word' => $total_word, 'total_character' => $total_character, 'is_product_type_variable' => $is_product_type_variable, 'woocommerce_currency_symbol_js' => get_woocommerce_currency_symbol(), 'woocommerce_price_num_decimals' => wc_get_price_decimals(), 'aewcppw_word_character' => $this->wppw_get_product_type(), 'aewcppw_allow_users_to_enter_qty' => $this->aewcppw_allow_users_to_enter_qty())));
         }
         wp_enqueue_script($this->plugin_name . '-bn', plugin_dir_url(__FILE__) . 'js/woocommerce-price-per-word-bn.js', array('jquery'), $this->version, false);
     }
 }
    /**
     * Get column value.
     *
     * @param mixed $item
     * @param string $column_name
     */
    public function column_default($item, $column_name)
    {
        global $product;
        if (!$product || $product->id !== $item->id) {
            $product = wc_get_product($item->id);
        }
        switch ($column_name) {
            case 'product':
                if ($sku = $product->get_sku()) {
                    echo $sku . ' - ';
                }
                echo $product->get_title();
                // Get variation data
                if ($product->is_type('variation')) {
                    $list_attributes = array();
                    $attributes = $product->get_variation_attributes();
                    foreach ($attributes as $name => $attribute) {
                        $list_attributes[] = wc_attribute_label(str_replace('attribute_', '', $name)) . ': <strong>' . $attribute . '</strong>';
                    }
                    echo '<div class="description">' . implode(', ', $list_attributes) . '</div>';
                }
                break;
            case 'parent':
                if ($item->parent) {
                    echo get_the_title($item->parent);
                } else {
                    echo '-';
                }
                break;
            case 'stock_status':
                if ($product->is_in_stock()) {
                    $stock_html = '<mark class="instock">' . __('In stock', 'woocommerce') . '</mark>';
                } else {
                    $stock_html = '<mark class="outofstock">' . __('Out of stock', 'woocommerce') . '</mark>';
                }
                echo apply_filters('woocommerce_admin_stock_html', $stock_html, $product);
                break;
            case 'stock_level':
                echo $product->get_stock_quantity();
                break;
            case 'wc_actions':
                ?>
<p>
					<?php 
                $actions = array();
                $action_id = $product->is_type('variation') ? $item->parent : $item->id;
                $actions['edit'] = array('url' => admin_url('post.php?post=' . $action_id . '&action=edit'), 'name' => __('Edit', 'woocommerce'), 'action' => "edit");
                if ($product->is_visible()) {
                    $actions['view'] = array('url' => get_permalink($action_id), 'name' => __('View', 'woocommerce'), 'action' => "view");
                }
                $actions = apply_filters('woocommerce_admin_stock_report_product_actions', $actions, $product);
                foreach ($actions as $action) {
                    printf('<a class="button tips %s" href="%s" data-tip="%s ' . __('product', 'woocommerce') . '">%s</a>', $action['action'], esc_url($action['url']), esc_attr($action['name']), esc_attr($action['name']));
                }
                ?>
				</p><?php 
                break;
        }
    }
Пример #25
0
/**
 * Update a product's stock status.
 *
 * @param  int $product_id
 * @param  int $status
 */
function wc_update_product_stock_status($product_id, $status)
{
    $product = wc_get_product($product_id);
    if ($product) {
        $product->set_stock_status($status);
        $product->save();
    }
}
 public function display_product_block()
 {
     global $post;
     $product = $GLOBALS['product'] = wc_get_product($post);
     $image = wp_get_attachment_image_src(get_post_thumbnail_id(), 'post');
     $image = $image[0];
     wc_get_template('single-product/introduction.php', compact('product', 'image'));
 }
 /**
  * Get the WC Product instance for a given product ID or post
  *
  * get_product() is soft-deprecated in WC 2.2
  *
  * @since 3.0.0
  * @param bool|int|string|\WP_Post $the_product
  * @param array $args
  * @return WC_Product
  */
 public static function wc_get_product($the_product = false, $args = array())
 {
     if (self::is_wc_version_gte_2_2()) {
         return wc_get_product($the_product, $args);
     } else {
         return get_product($the_product, $args);
     }
 }
 public function easy_booking_enqueue_admin_scripts()
 {
     global $post;
     $screen = get_current_screen();
     $this->options = get_option('easy_booking_settings');
     // Get page language in order to load Pickadate translation
     $site_language = get_bloginfo('language');
     $lang = str_replace('-', '_', $site_language);
     $admin_picker_script = '';
     // Concatenated and minified script including picker.js, picker.date.js and legacy.js
     wp_register_script('pickadate', plugins_url('assets/js/pickadate.min.js', WCEB_PLUGIN_FILE), array('jquery'), '1.0', true);
     // wp_register_script( 'picker', plugins_url( 'assets/js/dev/picker.js', WCEB_PLUGIN_FILE  ), array('jquery'), '1.0', true );
     // wp_register_script( 'picker.date', plugins_url( 'assets/js/dev/picker.date.js', WCEB_PLUGIN_FILE  ), array('jquery'), '1.0', true );
     // wp_register_script( 'legacy', plugins_url( 'assets/js/dev/legacy.js', WCEB_PLUGIN_FILE  ), array('jquery'), '1.0', true );
     // Calendar theme
     $theme = $this->options['easy_booking_calendar_theme'];
     if (function_exists('is_multisite') && is_multisite()) {
         $blog_id = get_current_blog_id();
         wp_register_style('picker', plugins_url('assets/css/' . $theme . '.' . $blog_id . '.min.css', WCEB_PLUGIN_FILE), true);
     } else {
         wp_register_style('picker', plugins_url('assets/css/' . $theme . '.min.css', WCEB_PLUGIN_FILE), true);
     }
     if (in_array($screen->id, array('product'))) {
         $product = wc_get_product($post->ID);
         wp_enqueue_script('ebs-admin-product', plugins_url('assets/js/admin/ebs-admin-product.min.js', WCEB_PLUGIN_FILE), array('jquery'), '1.0', true);
         // wp_enqueue_script( 'ebs-admin-product', plugins_url('assets/js/admin/dev/ebs-admin-product.js', WCEB_PLUGIN_FILE), array('jquery'), '1.0', true );
         wp_register_style('static-picker', plugins_url('assets/css/admin/static-picker.min.css', WCEB_PLUGIN_FILE), true);
         // wp_register_style( 'static-picker', plugins_url( 'assets/css/admin/dev/static-picker.css', WCEB_PLUGIN_FILE ), true);
         wp_enqueue_style('static-picker');
         $admin_picker_script = 'ebs-admin-product';
     }
     if (in_array($screen->id, array('shop_order'))) {
         // Calculation mode (Days or Nights)
         $calc_mode = $this->options['easy_booking_calc_mode'];
         wp_enqueue_script('pickadate-custom-admin', plugins_url('assets/js/admin/pickadate-custom-admin.min.js', WCEB_PLUGIN_FILE), array('jquery', 'pickadate'), '1.0', true);
         // wp_enqueue_script( 'pickadate-custom-admin', plugins_url('assets/js/admin/dev/pickadate-custom-admin.js', WCEB_PLUGIN_FILE), array('jquery', 'pickadate'), '1.0', true );
         wp_enqueue_style('picker');
         wp_localize_script('pickadate-custom-admin', 'order_ajax_info', array('ajax_url' => esc_url(admin_url('admin-ajax.php')), 'order_id' => $post->ID, 'calc_mode' => esc_html($calc_mode)));
         $admin_picker_script = 'pickadate-custom-admin';
     }
     if (in_array($screen->id, array('product')) || in_array($screen->id, array('shop_order'))) {
         wp_enqueue_script('pickadate');
         if (is_rtl()) {
             // Load Right to left CSS file
             wp_register_style('rtl-style', plugins_url('assets/css/rtl.min.css', WCEB_PLUGIN_FILE), true);
             // wp_register_style( 'rtl-style', plugins_url('assets/css/dev/rtl.css', WCEB_PLUGIN_FILE), true);
             wp_enqueue_style('rtl-style');
         }
         wp_enqueue_script('datepicker.language', plugins_url('assets/js/translations/' . $lang . '.js', WCEB_PLUGIN_FILE), array('jquery', 'pickadate', $admin_picker_script), '1.0', true);
     }
     // JS for admin notices
     // wp_enqueue_script( 'easy_booking_functions', plugins_url( 'assets/js/admin/dev/wceb-admin-functions.js', WCEB_PLUGIN_FILE ), array('jquery'), '1.0', true);
     wp_enqueue_script('easy_booking_functions', plugins_url('assets/js/admin/wceb-admin-functions.min.js', WCEB_PLUGIN_FILE), array('jquery'), '1.0', true);
     // CSS for admin notices
     wp_enqueue_style('easy_booking_notices', plugins_url('assets/css/admin/notices.min.css', WCEB_PLUGIN_FILE));
     // wp_enqueue_style( 'easy_booking_notices', plugins_url(  'assets/css/admin/dev/notices.css', WCEB_PLUGIN_FILE ) );
     wp_localize_script('easy_booking_functions', 'ajax_object', array('ajax_url' => esc_url(admin_url('admin-ajax.php'))));
 }
 /**
  * Plugin activation hook callback.
  *
  * @since 1.0.0
  */
 public function init()
 {
     // Add plugin custom roles and capabilities
     $this->_wwp_wholesale_roles->addCustomRole('wholesale_customer', 'Wholesale Customer');
     $this->_wwp_wholesale_roles->registerCustomRole('wholesale_customer', 'Wholesale Customer', array('desc' => 'This is the main wholesale user role.', 'main' => true));
     $this->_wwp_wholesale_roles->addCustomCapability('wholesale_customer', 'have_wholesale_price');
     // Get all wholesale roles
     $allWholesaleRoles = $this->_wwp_wholesale_roles->getAllRegisteredWholesaleRoles();
     // For each variable products, check each variation, check if it has a valid wholesale price
     // If so, get the variation id of that variation, then add it as a meta to the main variable product
     $args = array('post_type' => 'product', 'posts_per_page' => -1);
     $query = new WP_Query($args);
     while ($query->have_posts()) {
         $query->the_post();
         $product = wc_get_product(get_the_ID());
         // Since we are using add_post_meta, we need to delete that meta first
         // in order for it not to have a stacked up value.
         foreach ($allWholesaleRoles as $roleKey => $role) {
             delete_post_meta($product->id, $roleKey . '_variations_with_wholesale_price');
         }
         // Check if current product is a variable product
         if ($product->product_type == 'variable') {
             // If so, then get all variation of this variable product
             $varArgs = array('post_type' => 'product_variation', 'numberposts' => -1, 'post_parent' => $product->id);
             $variationQuery = new WP_Query($varArgs);
             // Variable product loop
             while ($variationQuery->have_posts()) {
                 $variationQuery->the_post();
                 foreach ($allWholesaleRoles as $roleKey => $role) {
                     $wholesalePrice = get_post_meta(get_the_ID(), $roleKey . '_wholesale_price', true);
                     if (is_numeric($wholesalePrice) && $wholesalePrice > 0) {
                         add_post_meta($product->id, $roleKey . '_variations_with_wholesale_price', get_the_ID());
                     }
                 }
             }
             // Meta that serves as the main meta to mark the product if has a valid wholesale price
             foreach ($allWholesaleRoles as $roleKey => $role) {
                 $postMeta = get_post_meta($product->id, $roleKey . '_variations_with_wholesale_price');
                 if (!empty($postMeta)) {
                     update_post_meta($product->id, $roleKey . '_have_wholesale_price', 'yes');
                 } else {
                     update_post_meta($product->id, $roleKey . '_have_wholesale_price', 'no');
                 }
             }
         } elseif ($product->product_type == 'simple') {
             // Meta that serves as the main meta to mark the product if has a valid wholesale price
             foreach ($allWholesaleRoles as $roleKey => $role) {
                 $wholesalePrice = get_post_meta($product->id, $roleKey . '_wholesale_price', true);
                 if (is_numeric($wholesalePrice) && $wholesalePrice > 0) {
                     update_post_meta($product->id, $roleKey . '_have_wholesale_price', 'yes');
                 } else {
                     update_post_meta($product->id, $roleKey . '_have_wholesale_price', 'no');
                 }
             }
         }
     }
     wp_reset_postdata();
 }
Пример #30
-1
 /**
  * Find the order active number (completed or processing ) for a given user on a course. It will return the latest order.
  *
  * If multiple exist we will return the latest order.
  *
  * @param $user_id
  * @param $course_id
  * @return array $user_course_orders
  */
 public static function get_learner_course_active_order_id($user_id, $course_id)
 {
     $course_product_id = get_post_meta($course_id, '_course_woocommerce_product', true);
     $orders_query = new WP_Query(array('post_type' => 'shop_order', 'posts_per_page' => -1, 'post_status' => array('wc-processing', 'wc-completed'), 'meta_key' => '_customer_user', 'meta_value' => $user_id));
     if ($orders_query->post_count == 0) {
         return false;
     }
     foreach ($orders_query->get_posts() as $order) {
         $order = new WC_Order($order->ID);
         $items = $order->get_items();
         $user_orders = array();
         foreach ($items as $item) {
             // if the product id on the order and the one given to this function
             // this order has been placed by the given user on the given course.
             $product = wc_get_product($item['product_id']);
             if ($product->is_type('variable')) {
                 $item_product_id = $item['variation_id'];
             } else {
                 $item_product_id = $item['product_id'];
             }
             if ($course_product_id == $item_product_id) {
                 return $order->id;
             }
         }
         //end for each order item
     }
     // end for each order
     // if we reach this place we found no order
     return false;
 }