public static function get_test_product() { $products = get_posts(array('post_type' => 'product')); if (count($products) == 0) { TaxJar_Helper_Product::create_test_product(); $products = get_posts(array('post_type' => 'product')); } $factory = new WC_Product_Factory(); return $factory->get_product($products[0]->ID); }
public function simple_product_xml($merchantID, $awsAccessKeyID) { global $wpdb; $client_id = ''; $prefix = $wpdb->prefix; $table = $prefix . "pwa_before_cart_save"; $sess_data = new WC_Session_Handler(); $sess_detail = $sess_data->get_session_cookie(); $sess_cust_id = $sess_detail[0]; if (is_user_logged_in()) { $user_ID = get_current_user_id(); } else { $user_ID = 0; } if (UPDATE_ODER_FROM == 'woocart') { $query = 'SELECT id FROM ' . $table . ' where user_id = "' . $user_ID . '" ORDER BY id DESC LIMIT 1'; $result = $wpdb->get_results($query); $client_id = $result[0]->id; } else { $client_id = $user_ID; } $doc = new DOMDocument('1.0'); $doc->formatOutput = true; $root = $doc->createElement('Order'); $attribute = $doc->createAttribute('xmlns'); $attribute->value = 'http://payments.amazon.com/checkout/2009-05-15/'; $root_attr = $root->appendChild($attribute); $root = $doc->appendChild($root); $ClientRequestId = $doc->createElement('ClientRequestId', $client_id); $ClientRequestId = $root->appendChild($ClientRequestId); $Cart = $doc->createElement('Cart'); $Cart = $root->appendChild($Cart); $Items = $doc->createElement('Items'); $Items = $Cart->appendChild($Items); $CartPromotionId = $doc->createElement('CartPromotionId', 'Total_Discount'); $CartPromotionId = $Cart->appendChild($CartPromotionId); $Promotions = $doc->createElement('Promotions'); $Promotions = $root->appendChild($Promotions); $cartObj = WC()->cart; $all_fees = $cartObj->get_fees(); $real_cart = WC()->cart->get_cart(); $_pf = new WC_Product_Factory(); $currency = get_woocommerce_currency(); $cart_total = 0; $total_fees = 0; $cart_total_wocom = WC()->cart->total; $cart_subtotal = $cartObj->subtotal; $amazon_total_disc = 0; $cart_discount_amount = $cartObj->get_cart_discount_total(); $cart_coupon_code = ''; if (!empty($cartObj->coupon_discount_tax_amounts)) { foreach ($cartObj->coupon_discount_tax_amounts as $key => $coupon) { $cart_coupon_code .= $key . ","; $cart_discount_amount += $coupon; } } else { $cart_discount_amount = (double) $cartObj->discount_cart + (double) $cartObj->discount_total; } $neg_fees_Amout = 0; foreach ($all_fees as $fee) { $fees_Amout = $fee->amount + $fee->tax; if ($fees_Amout < 0) { $neg_fees_Amout = abs($fees_Amout); } } $cart_discount_amount += $neg_fees_Amout; $cart_discount_amount = (double) $cart_discount_amount; if ($cart_discount_amount) { $Promotion = $doc->createElement('Promotion'); $Promotion = $Promotions->appendChild($Promotion); $Promotion_pro_id = $doc->createElement('PromotionId', 'Total_Discount'); $Promotion_pro_id = $Promotion->appendChild($Promotion_pro_id); $Promotion_pro_desc = $doc->createElement('Description', 'desc'); $Promotion_pro_desc = $Promotion->appendChild($Promotion_pro_desc); $Promotion_pro_benf = $doc->createElement('Benefit'); $Promotion_pro_benf = $Promotion->appendChild($Promotion_pro_benf); $Promotion_pro_benf_fad = $doc->createElement('FixedAmountDiscount'); $Promotion_pro_benf_fad = $Promotion_pro_benf->appendChild($Promotion_pro_benf_fad); $Promotion_pro_benf_fad_amount = $doc->createElement('Amount', $cart_discount_amount); $Promotion_pro_benf_fad_amount = $Promotion_pro_benf_fad->appendChild($Promotion_pro_benf_fad_amount); $Promotion_pro_benf_fad_currency = $doc->createElement('CurrencyCode', $currency); $Promotion_pro_benf_fad_currency = $Promotion_pro_benf_fad->appendChild($Promotion_pro_benf_fad_currency); } foreach ($real_cart as $key => $item) { $product_id = isset($item['variation_id']) && $item['variation_id'] != '' ? $item['variation_id'] : $item['product_id']; $variation_id = $item['variation_id']; $productObj = new WC_Product($product_id); $product = $_pf->get_product($product_id); $sku = $product->get_sku(); $sku = substr($sku, 0, 40); $title = $product->get_title(); if (!$title) { $title = 'Title'; } $title = substr($title, 0, 80); $description = $product->get_post_data()->post_content; $description = substr($description, 0, 1900); $quantity = $item['quantity']; $weight = $product->get_weight(); $weight_unit = get_option('woocommerce_weight_unit'); if ($weight_unit != 'kg' && $weight > 0) { $weight = $weight / 1000; $weight_unit = 'kg'; } $variations = isset($item['variation']) && $item['variation'] != '' ? $item['variation'] : array(); if ($cartObj->prices_include_tax) { $product_price = ($item['line_subtotal'] + $item['line_subtotal_tax']) / $quantity; } else { $product_price = $item['line_subtotal'] / $quantity; } $amazon_product_price = ($item['line_subtotal'] + $item['line_subtotal_tax']) / $quantity; $cart_total += $amazon_end_line_subtotal; /** create xml of the basic product **/ $Item = $doc->createElement('Item'); $Item = $Items->appendChild($Item); $sku = $this->replace_char($sku); $sku = htmlentities($sku, ENT_QUOTES, 'UTF-8'); $SKU = $doc->createElement('SKU', $sku); $SKU = $Item->appendChild($SKU); $MerchantId = $doc->createElement('MerchantId', $merchantID); $MerchantId = $Item->appendChild($MerchantId); $title = $this->replace_char($title); $title = htmlentities($title, ENT_QUOTES, 'UTF-8'); $Title = $doc->createElement('Title', $title); $Title = $Item->appendChild($Title); $description = $this->replace_char($description); $description = htmlentities($description, ENT_QUOTES, 'UTF-8'); $Description = $doc->createElement('Description', $description); $Description = $Item->appendChild($Description); $Price = $doc->createElement('Price'); $Price = $Item->appendChild($Price); $Amount = $doc->createElement('Amount', $amazon_product_price); $Amount = $Price->appendChild($Amount); $CurrencyCode = $doc->createElement('CurrencyCode', $currency); $CurrencyCode = $Price->appendChild($CurrencyCode); $Quantity = $doc->createElement('Quantity', $quantity); $Quantity = $Item->appendChild($Quantity); if ($weight) { $Weight = $doc->createElement('Weight'); $Weight = $Item->appendChild($Weight); $Amount_wt = $doc->createElement('Amount', $weight); $Amount_wt = $Weight->appendChild($Amount_wt); $Wt_unit = $doc->createElement('Unit', $weight_unit); $Wt_unit = $Weight->appendChild($Wt_unit); } $ItemCustomData = $doc->createElement('ItemCustomData'); $ItemCustomData = $Item->appendChild($ItemCustomData); $Product_id = $doc->createElement('Product_id', $item['product_id']); $Product_id = $ItemCustomData->appendChild($Product_id); $Variation_id = $doc->createElement('Variation_id', $variation_id); $Variation_id = $ItemCustomData->appendChild($Variation_id); foreach ($variations as $key => $variant) { $Item_attribute = $doc->createElement('Item_attribute'); $Item_attribute = $ItemCustomData->appendChild($Item_attribute); $key = substr($key, 0, 40); $key = $this->replace_char($key); $key = htmlentities($key, ENT_QUOTES, 'UTF-8'); $Attribute_name = $doc->createElement('Attribute_name', $key); $Attribute_name = $Item_attribute->appendChild($Attribute_name); $variant = substr($variant, 0, 40); $variant = $this->replace_char($variant); $variant = htmlentities($variant, ENT_QUOTES, 'UTF-8'); $Attribute_val = $doc->createElement('Attribute_val', $variant); $Attribute_val = $Item_attribute->appendChild($Attribute_val); } } foreach ($all_fees as $fee) { $fees_Amout = $fee->amount + $fee->tax; if ($fees_Amout > 0) { $Item = $doc->createElement('Item'); $Item = $Items->appendChild($Item); $fee_id = substr($fee->id, 0, 40); $fee_id = $this->replace_char($fee_id); $fee_id = htmlentities($fee_id, ENT_QUOTES, 'UTF-8'); $SKU = $doc->createElement('SKU', $fee_id); $SKU = $Item->appendChild($SKU); $MerchantId = $doc->createElement('MerchantId', $merchantID); $MerchantId = $Item->appendChild($MerchantId); $fee_name = substr($fee->name, 0, 80); if (!$fee_name) { $fee_name = 'Order Fees'; } $fee_name = $this->replace_char($fee_name); $fee_name = htmlentities($fee_name, ENT_QUOTES, 'UTF-8'); $Title = $doc->createElement('Title', $fee_name); $Title = $Item->appendChild($Title); $Description = $doc->createElement('Description', 'extra fees'); $Description = $Item->appendChild($Description); $Price = $doc->createElement('Price'); $Price = $Item->appendChild($Price); $Amount = $doc->createElement('Amount', $fees_Amout); $Amount = $Price->appendChild($Amount); $CurrencyCode = $doc->createElement('CurrencyCode', $currency); $CurrencyCode = $Price->appendChild($CurrencyCode); $Quantity = $doc->createElement('Quantity', 1); $Quantity = $Item->appendChild($Quantity); } } return $doc->saveXML(); }
function post_object($id, $term_id = false, $matches = false) { $unset_array = array('post_date_gmt', 'post_status', 'comment_status', 'ping_status', 'post_password', 'post_content_filtered', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'guid', 'menu_order', 'post_mime_type', 'comment_count', 'ancestors', 'filter'); global $post; $date_format = get_option('date_format'); $post = get_post($id); if ($term_id) { if (!in_category($term_id, $post->ID)) { return false; } } $size = array('height' => 50, 'width' => 50); if ($post != null) { $post_object = new stdclass(); $post_link = get_permalink($post->ID); if (in_array('{post_image}', $matches) || in_array('{post_image_html}', $matches)) { $post_thumbnail_id = get_post_thumbnail_id($post->ID); if ($post_thumbnail_id > 0) { $thumb = wp_get_attachment_image_src($post_thumbnail_id, array($size['height'], $size['width'])); $post_object->post_image = trim($thumb[0]) == "" ? WEBNUS_SEARCH_NO_IMAGE : $thumb[0]; if (in_array('{post_image_html}', $matches)) { $post_object->post_image_html = '<img src="' . $post_object->post_image . '" width="' . $size['width'] . '" height="' . $size['height'] . '"/>'; } } else { if ($src = $this->get_image_from_content($post->post_content, $size['height'], $size['width'])) { $post_object->post_image = $src['src'] ? $src['src'] : WEBNUS_SEARCH_NO_IMAGE; if (in_array('{post_image_html}', $matches)) { $post_object->post_image_html = '<img src="' . $post_object->post_image . '" width="' . $src['width'] . '" height="' . $src['height'] . '" />'; } } else { $post_object->post_image = WEBNUS_SEARCH_NO_IMAGE; if (in_array('{post_image_html}', $matches)) { $post_object->post_image_html = ''; } } } } if ($post->post_type == "wpsc-product") { if (function_exists('wpsc_calculate_price')) { if (in_array('{wpsc_price}', $matches)) { $post_object->wpsc_price = wpsc_the_product_price(); } if (in_array('{wpsc_shipping}', $matches)) { $post_object->wpsc_shipping = strip_tags(wpsc_product_postage_and_packaging()); } if (in_array('{wpsc_image}', $matches)) { $post_object->wpsc_image = wpsc_the_product_image($size['height'], $size['width']); } } } if ($post->post_type == 'product' && class_exists('WC_Product_Factory')) { $product_factory = new WC_Product_Factory(); global $product; $product = $product_factory->get_product($post); if ($product->is_visible()) { foreach ($matches as $match) { $match = str_replace(array('{', '}'), '', $match); if (in_array($match, array('categories', 'tags'))) { $method = "get_" . $match; if (method_exists($product, $method)) { $term_list = call_user_func(array($product, $method), ''); if ($term_list) { $post_object->{$match} = '<span class="sf_list sf_' . $match . '">' . $term_list . '</span>'; } else { $post_object->{$match} = ""; } } } elseif ($match == 'add_to_cart_button') { ob_start(); do_action('woocommerce_' . $product->product_type . '_add_to_cart'); $post_object->{$match} = '<div class="product">' . ob_get_contents() . '</div>'; ob_end_clean(); } else { $method = "get_" . $match; if (method_exists($product, $method)) { $post_object->{$match} = call_user_func(array($product, $method)); } elseif (method_exists($product, $match)) { $post_object->{$match} = call_user_func(array($product, $match)); } } } } /* $post->sku = $product->get_sku(); $post->sale_price = $product->get_sale_price(); $post->regular_price = $product->get_regular_price(); $post->price = $product->get_price(); $post->price_including_tax = $product->get_price_including_tax(); $post->price_excluding_tax = $product->get_price_excluding_tax(); $post->price_suffix = $product->get_price_suffix(); $post->price_html = $product->get_price_html(); $post->price_html_from_text = $product->get_price_html_from_text(); $post->average_rating = $product->get_average_rating(); $post->rating_count = $product->get_rating_count(); $post->rating_html = $product->get_rating_html(); $post->dimensions = $product->get_dimensions(); $post->shipping_class = $product->get_shipping_class(); $post->add_to_cart_text = $product->add_to_cart_text(); $post->single_add_to_cart_text = $product->single_add_to_cart_text(); $post->add_to_cart_url = $product->add_to_cart_url(); $post->title = $product->get_title(); */ } $post_object->ID = $post->ID; $post_object->post_title = get_the_title($post->ID); if (in_array('{post_excerpt}', $matches)) { $post_object->post_excerpt = $post->post_excerpt; } if (in_array('{post_author}', $matches)) { $post_object->post_author = get_the_author_meta('display_name', $post->post_author); } if (in_array('{post_link}', $matches)) { $post_object->post_link = $post_link; } if (in_array('{post_content}', $matches)) { $post_object->post_content = $this->get_text_words(apply_filters('the_content', $post->post_content), (int) $this->get_excerpt_count()); } if (in_array('{post_date_formatted}', $matches)) { $post_object->post_date_formatted = date($date_format, strtotime($post->post_date)); } foreach ($matches as $match) { $match = str_replace(array('{', '}'), '', $match); if (strpos($match, 'custom_field_') !== false) { $key = str_replace('custom_field_', '', $match); $custom_field = get_post_meta($post->ID, $key, true); if (is_array($custom_field)) { $cf_name = 'custom_field_' . $key; $post_object->{$cf_name} = apply_filters('sf_post_custom_field', $custom_field[0], $key, $post); } else { $cf_name = 'custom_field_' . $key; $post_object->{$cf_name} = apply_filters('sf_post_custom_field', $custom_field, $key, $post); } } } $post_object = apply_filters('sf_post', $post_object); return $post_object; } return false; }
/** * Gets product without injecting gzd_product. Only available as fallback * * @param bool $the_product (default: false) * @param array $args (default: array()) * @return WC_Product|bool false if the product cannot be loaded */ public function get_product_standalone($the_product = false, $args = array()) { return parent::get_product($the_product, $args); }
/** * Prepare a single product for create or update. * * @param WP_REST_Request $request Request object. * @return WP_Error|stdClass $data Post object. */ protected function prepare_item_for_database($request) { if (isset($request['id'])) { $product = wc_get_product(absint($request['id'])); } else { $classname = WC_Product_Factory::get_classname_from_product_type($request['type']); if (!class_exists($classname)) { $classname = 'WC_Product_Simple'; } $product = new $classname(); } // Post title. if (isset($request['name'])) { $product->set_name(wp_filter_post_kses($request['name'])); } // Post content. if (isset($request['description'])) { $product->set_description(wp_filter_post_kses($request['description'])); } // Post excerpt. if (isset($request['short_description'])) { $product->set_short_description(wp_filter_post_kses($request['short_description'])); } // Post status. if (isset($request['status'])) { $product->set_status(get_post_status_object($request['status']) ? $request['status'] : 'draft'); } // Post slug. if (isset($request['slug'])) { $product->set_slug($request['slug']); } // Menu order. if (isset($request['menu_order'])) { $product->set_menu_order($request['menu_order']); } // Comment status. if (!empty($request['reviews_allowed'])) { $product->set_reviews_allowed($request['reviews_allowed']); } /** * Filter the query_vars used in `get_items` for the constructed query. * * The dynamic portion of the hook name, $this->post_type, refers to post_type of the post being * prepared for insertion. * * @param WC_Product $product An object representing a single item prepared * for inserting or updating the database. * @param WP_REST_Request $request Request object. */ return apply_filters("woocommerce_rest_pre_insert_{$this->post_type}", $product, $request); }
function discount_when_room_winter_in_cart() { global $woocommerce; $cart = $woocommerce->cart->get_cart(); $_pf = new WC_Product_Factory(); foreach ($cart as $item) { $_product = $_pf->get_product($item['product_id']); if (TauchTerminal_Tulamben::isRoomProduct($_product->get_sku())) { $winderDays = 0; $start = strtotime($item['start_date']); $end = strtotime($item['end_date']); $threemonths = strtotime("+3 months", strtotime(date('Y-m-d'))); $wstart = strtotime(TauchTerminal_DB::getTTOption('winter_start')); $wend = strtotime(TauchTerminal_DB::getTTOption('winter_end')); if ($start >= $wstart && $end <= $wend) { $winderDays += floor(($end - $start) / (60 * 60 * 24)); // var_dump('all days'); } else { if ($start >= $wstart) { $winderDays += floor(($wend - $start) / (60 * 60 * 24)); // var_dump('start in season'); } else { if ($end <= $wend) { $winderDays += floor(($end - $wstart) / (60 * 60 * 24)); // var_dump('End in season'); } } } if ($winderDays != 0) { $title = 'Winter Season' . "\n" . $winderDays . ' Day'; if ($winderDays > 1) { $title .= 's'; } $discount = floatval(TauchTerminal_DB::getTTOption('winter_discount')) * $winderDays * -1; $woocommerce->cart->add_fee($title, $discount, true, ''); // Early bird if ($start >= $threemonths) { $_product = new WC_Product_Variation($item['variation_id']); $discountP = floatval(TauchTerminal_DB::getTTOption('earlybird')); $price = floatval(preg_replace('#[^\\d.]#', '', $woocommerce->cart->get_product_price($_product))); $discount = $price * $discountP / 100 * $winderDays * -1; $title = 'Earlybird ' . $discountP . '%' . "\n" . 'for ' . $winderDays . ' Day'; if ($winderDays > 1) { $title .= 's'; } $woocommerce->cart->add_fee($title, $discount, true, ''); } } } } }
/** * Fetches product stock for every product in Woo from Fortnox * * @return bool */ public function SKU_clean() { $args = array('post_type' => array('product', 'product_variation'), 'orderby' => 'id', 'posts_per_page' => -1); $the_query = new WP_Query($args); logthis("BEGINNING"); $index = 0; foreach ($the_query->get_posts() as $fetched_product) { $pf = new WC_Product_Factory(); $product = $pf->get_product($fetched_product->ID); if ($product->has_child()) { foreach ($product->get_children() as $child_id) { logthis($child_id); $child = $pf->get_product($child_id); $sku = $child->get_sku(); $sku = $this->clean_str($sku); update_post_meta($child_id, '_sku', $sku); $index++; } } else { logthis($fetched_product->ID); $sku = $product->get_sku(); $sku = $this->clean_str($sku); update_post_meta($fetched_product->ID, '_sku', $sku); $index++; } } return "SKUs cleaned: " . $index; }
/** * Create a new product * * @since 2.2 * @param array $data posted data * @return array */ public function create_product($data) { $id = 0; try { if (!isset($data['product'])) { throw new WC_API_Exception('woocommerce_api_missing_product_data', sprintf(__('No %1$s data specified to create %1$s', 'woocommerce'), 'product'), 400); } $data = $data['product']; // Check permissions if (!current_user_can('publish_products')) { throw new WC_API_Exception('woocommerce_api_user_cannot_create_product', __('You do not have permission to create products', 'woocommerce'), 401); } $data = apply_filters('woocommerce_api_create_product_data', $data, $this); // Check if product title is specified if (!isset($data['title'])) { throw new WC_API_Exception('woocommerce_api_missing_product_title', sprintf(__('Missing parameter %s', 'woocommerce'), 'title'), 400); } // Check product type if (!isset($data['type'])) { $data['type'] = 'simple'; } // Set visible visibility when not sent if (!isset($data['catalog_visibility'])) { $data['catalog_visibility'] = 'visible'; } // Validate the product type if (!in_array(wc_clean($data['type']), array_keys(wc_get_product_types()))) { throw new WC_API_Exception('woocommerce_api_invalid_product_type', sprintf(__('Invalid product type - the product type must be any of these: %s', 'woocommerce'), implode(', ', array_keys(wc_get_product_types()))), 400); } // Enable description html tags. $post_content = isset($data['description']) ? wc_clean($data['description']) : ''; if ($post_content && isset($data['enable_html_description']) && true === $data['enable_html_description']) { $post_content = $data['description']; } // Enable short description html tags. $post_excerpt = isset($data['short_description']) ? wc_clean($data['short_description']) : ''; if ($post_excerpt && isset($data['enable_html_short_description']) && true === $data['enable_html_short_description']) { $post_excerpt = $data['short_description']; } $classname = WC_Product_Factory::get_classname_from_product_type($data['type']); if (!class_exists($classname)) { $classname = 'WC_Product_Simple'; } $product = new $classname(); $product->set_name(wc_clean($data['title'])); $product->set_status(isset($data['status']) ? wc_clean($data['status']) : 'publish'); $product->set_short_description(isset($data['short_description']) ? $post_excerpt : ''); $product->set_description(isset($data['description']) ? $post_content : ''); // Attempts to create the new product. $product->create(); $id = $product->get_id(); // Checks for an error in the product creation if (0 >= $id) { throw new WC_API_Exception('woocommerce_api_cannot_create_product', $id->get_error_message(), 400); } // Check for featured/gallery images, upload it and set it if (isset($data['images'])) { $product = $this->save_product_images($product, $data['images']); } // Save product meta fields $product = $this->save_product_meta($product, $data); $product->save(); // Save variations if (isset($data['type']) && 'variable' == $data['type'] && isset($data['variations']) && is_array($data['variations'])) { $this->save_variations($product, $data); } do_action('woocommerce_api_create_product', $id, $data); // Clear cache/transients wc_delete_product_transients($id); $this->server->send_status(201); return $this->get_product($id); } catch (WC_Data_Exception $e) { $this->clear_product($id); return new WP_Error($e->getErrorCode(), $e->getMessage(), array('status' => $e->getCode())); } catch (WC_API_Exception $e) { $this->clear_product($id); return new WP_Error($e->getErrorCode(), $e->getMessage(), array('status' => $e->getCode())); } }
function yf_woocommerce_checkout_update_order_review($post_data) { global $woocommerce; parse_str($post_data, $post_data); /*_print($post_data); _print($woocommerce->cart->cart_contents);*/ if (empty($post_data['_esc_field_amount_another'])) { return; } foreach ($woocommerce->cart->cart_contents as $key => $value) { $_pf = new WC_Product_Factory(); $_product = $_pf->get_product($value['data']->id); $value['data']->price = $post_data['_esc_field_amount_another']; } //exit; }
* Variables Definition */ $batch_count = 100; $attributesToSnippet = array("content"); /** * Defaults Variables */ $attributesToIndex = array("title", "excerpt", "content", "author", "type"); /** * Handling Extension */ $external_attrs = array(); $external_attrs['product_attrs'] = array('virtual', 'sku', 'taxable', 'tax_status', 'tax_class', 'managing_stock', 'stock_quantity', 'in_stock', 'backorders_allowed', 'sold_individually', 'purchaseable', 'visible', 'catalog_visibility', 'on_sale', 'weight', 'length', 'shipping_required', 'shipping_taxable', 'shipping_class', 'shipping_class_id', 'reviews_allowed', 'average_rating', 'rating_count', 'related_ids', 'upsell_ids', 'download_type', 'purchase_note'); $external_attrs['product'] = function ($data) { if (class_exists('WC_Product_Factory')) { $factory = new WC_Product_Factory(); $product = $factory->get_product($data->ID); $product_attrs = array('virtual' => $product->is_virtual(), 'sku' => $product->get_sku(), 'taxable' => $product->is_taxable(), 'tax_status' => $product->get_tax_status(), 'tax_class' => $product->get_tax_class(), 'managing_stock' => $product->managing_stock(), 'stock_quantity' => (int) $product->get_stock_quantity(), 'in_stock' => $product->is_in_stock(), 'backorders_allowed' => $product->backorders_allowed(), 'sold_individually' => $product->is_sold_individually(), 'purchaseable' => $product->is_purchasable(), 'visible' => $product->is_visible(), 'catalog_visibility' => $product->visibility, 'on_sale' => $product->is_on_sale(), 'weight' => $product->get_weight() ? wc_format_decimal($product->get_weight(), 2) : null, 'length' => $product->length, 'shipping_required' => $product->needs_shipping(), 'shipping_taxable' => $product->is_shipping_taxable(), 'shipping_class' => $product->get_shipping_class(), 'shipping_class_id' => 0 !== $product->get_shipping_class_id() ? $product->get_shipping_class_id() : null, 'reviews_allowed' => 'open' === $product->get_post_data()->comment_status, 'average_rating' => wc_format_decimal($product->get_average_rating(), 2), 'rating_count' => (int) $product->get_rating_count(), 'related_ids' => array_map('absint', array_values($product->get_related())), 'upsell_ids' => array_map('absint', $product->get_upsells()), 'download_type' => $product->download_type, 'purchase_note' => wpautop(do_shortcode(wp_kses_post($product->purchase_note)))); foreach ($product->get_attributes() as $attribute) { $product_attrs[$attribute['name']] = $attribute['value']; } return $product_attrs; } return array(); }; /** * Functions definitions */ function get_meta_key_list($type) { global $wpdb;
/** * Save meta box data. */ public static function save($post_id, $post) { // Process product type first so we have the correct class to run setters. $product_type = empty($_POST['product-type']) ? 'simple' : sanitize_title(stripslashes($_POST['product-type'])); $classname = WC_Product_Factory::get_classname_from_product_type($product_type); if (!class_exists($classname)) { $classname = 'WC_Product_Simple'; } $product = new $classname($post_id); $attributes = self::prepare_attributes(); $errors = $product->set_props(array('sku' => isset($_POST['_sku']) ? wc_clean($_POST['_sku']) : null, 'purchase_note' => wp_kses_post(stripslashes($_POST['_purchase_note'])), 'downloadable' => isset($_POST['_downloadable']), 'virtual' => isset($_POST['_virtual']), 'featured' => isset($_POST['_featured']), 'catalog_visibility' => wc_clean($_POST['_visibility']), 'tax_status' => wc_clean($_POST['_tax_status']), 'tax_class' => wc_clean($_POST['_tax_class']), 'weight' => wc_clean($_POST['_weight']), 'length' => wc_clean($_POST['_length']), 'width' => wc_clean($_POST['_width']), 'height' => wc_clean($_POST['_height']), 'shipping_class_id' => absint($_POST['product_shipping_class']), 'sold_individually' => !empty($_POST['_sold_individually']), 'upsell_ids' => array_map('intval', explode(',', $_POST['upsell_ids'])), 'cross_sell_ids' => array_map('intval', explode(',', $_POST['crosssell_ids'])), 'regular_price' => wc_clean($_POST['_regular_price']), 'sale_price' => wc_clean($_POST['_sale_price']), 'date_on_sale_from' => wc_clean($_POST['_sale_price_dates_from']), 'date_on_sale_to' => wc_clean($_POST['_sale_price_dates_to']), 'manage_stock' => !empty($_POST['_manage_stock']), 'backorders' => wc_clean($_POST['_backorders']), 'stock_status' => wc_clean($_POST['_stock_status']), 'stock_quantity' => wc_stock_amount($_POST['_stock']), 'download_limit' => '' === $_POST['_download_limit'] ? '' : absint($_POST['_download_limit']), 'download_expiry' => '' === $_POST['_download_expiry'] ? '' : absint($_POST['_download_expiry']), 'downloads' => self::prepare_downloads(isset($_POST['_wc_file_names']) ? $_POST['_wc_file_names'] : array(), isset($_POST['_wc_file_urls']) ? $_POST['_wc_file_urls'] : array(), isset($_POST['_wc_file_hashes']) ? $_POST['_wc_file_hashes'] : array()), 'product_url' => esc_url_raw($_POST['_product_url']), 'button_text' => wc_clean($_POST['_button_text']), 'children' => 'grouped' === $product_type ? self::prepare_children() : null, 'reviews_allowed' => !empty($_POST['_reviews_allowed']), 'attributes' => $attributes, 'default_attributes' => self::prepare_set_attributes($attributes, 'default_attribute_'))); if (is_wp_error($errors)) { WC_Admin_Meta_Boxes::add_error($errors->get_error_message()); } $product->save(); do_action('woocommerce_process_product_meta_' . $product_type, $post_id); }
"; twitter = "<?php echo ot_get_option('twitter'); ?> "; instagram = "<?php echo ot_get_option('instagram'); ?> "; products = []; <?php $args = array('post_type' => 'product'); $query = new WP_Query($args); if ($query->have_posts()) { $factory = new WC_Product_Factory(); while ($query->have_posts()) { $query->the_post(); $regular_price = get_post_meta(get_the_ID(), '_regular_price'); $sale_price = get_post_meta(get_the_ID(), '_sale_price'); $attributes = $factory->get_product(get_the_ID())->get_attributes(); // get product by id $i = 0; $length = count($attributes); $str = ""; foreach ($attributes as $key => $value) { $i++; if ($i == $length) { break; } $str = $str . "<div>" . "<span>" . $value['name'] . "</span>" . "<span>" . $value['value'] . "</span>" . "</div>";
/** * When the post is published, send the messages. * @param int $ID * @param obj $post */ function twp_post_published($ID, $post) { global $wpdb; global $table_name; global $tdata; if (isset($_POST['twp_send_to_channel'])) { update_post_meta($ID, '_twp_send_to_channel', $_POST['twp_send_to_channel']); # Load global options # p_ prefix stands for $_POST data $tcp = $tdata['twp_channel_pattern']->option_value; $tst = $tdata['twp_send_thumb']->option_value; if ($tcp != $_POST['twp_channel_pattern']) { $p_tcp = $_POST['twp_channel_pattern']; update_post_meta($ID, '_twp_meta_pattern', $p_tcp); } else { update_post_meta($ID, '_twp_meta_pattern', $tcp); } if ($tst != $_POST['twp_send_thumb']) { $p_tst = $_POST['twp_send_thumb']; update_post_meta($ID, '_twp_send_thumb', $p_tst); } else { update_post_meta($ID, '_twp_send_thumb', $tst); } if (isset($_POST['twp_img_id'])) { update_post_meta($ID, '_twp_img_id', $_POST['twp_img_id']); } } else { update_post_meta($ID, '_twp_send_to_channel', 0); } # Checks whether user wants to send this post to channel. if (get_post_meta($ID, '_twp_send_to_channel', true) == 1) { $pattern = get_post_meta($ID, '_twp_meta_pattern', true); if ($pattern == "" || $pattern == false) { $pattern = $tdata['twp_channel_pattern']->option_value; } if (!in_array('_twp_send_thumb', get_post_custom_keys($ID))) { $thumb_method = $tdata['twp_send_thumb']->option_value; } else { $thumb_method = get_post_meta($ID, '_twp_send_thumb', true); } } # If there is no pattern then return! if ($pattern == "") { return; } switch ($thumb_method) { case 1: $method = 'photo'; $photo = get_attached_file(get_post_thumbnail_id($ID)); break; case 2: $method = 'photo'; $photo = get_attached_file(get_post_meta($ID, '_twp_img_id', true)); break; default: $method = false; break; } # Initialize Telegram information $ch_name = $tdata['twp_channel_username']->option_value; $token = $tdata['twp_bot_token']->option_value; $web_preview = $tdata['twp_web_preview']->option_value; if ($token == "" || $ch_name == "") { update_post_meta($ID, '_twp_meta_data', __('Bot token or Channel username aren\'t set!', 'twp-plugin')); return; } if ($post->post_type == 'product') { $_pf = new WC_Product_Factory(); $product = $_pf->get_product($ID); $tags_array = explode(', ', $product->get_tags()); $categories_array = explode(', ', $product->get_categories()); } else { $tags_array = wp_get_post_tags($ID, array('fields' => 'names')); $categories_array = wp_get_post_categories($ID, array('fields' => 'names')); } foreach ($tags_array as $tag) { $tags .= " #" . $tag; } foreach ($categories_array as $cat) { $categories .= "|" . $cat; } $nt = new Notifcaster_Class(); switch ($tdata['twp_markdown']->option_value) { case 0: $format = null; break; case 1: $format = "markdown"; break; case 2: $format = "html"; break; default: $format = null; break; } $nt->_telegram($token, $format, $web_preview); # Preparing message for sending #Wordpress default tags and substitutes array $wp_tags = array("{title}", "{excerpt}", "{content}", "{author}", "{short_url}", "{full_url}", "{tags}", "{categories}"); $wp_subs = array($post->post_title, wp_trim_words($post->post_content, 55, "..."), $post->post_content, get_the_author_meta("display_name", $post->post_author), wp_get_shortlink($ID), get_permalink($ID), $tags, $categories); #WooCommerce tags and substitutes array $wc_tags = array("{width}", "{length}", "{height}", "{weight}", "{price}", "{regular_price}", "{sale_price}", "{sku}", "{stock}", "{downloadable}", "{virtual}", "{sold_indiidually}", "{tax_status}", "{tax_class}", "{stock_status}", "{backorders}", "{featured}", "{visibility}"); if ($post->post_type == 'product') { $p = $product; $wc_subs = array($p->width, $p->length, $p->height, $p->weight, $p->price, $p->regular_price, $p->sale_price, $p->sku, $p->stock, $p->downloadable, $p->virtual, $p->sold_individually, $p->tax_status, $p->tax_class, $p->stock_status, $p->backorders, $p->featured, $p->visibility); } # The variables are case-sensitive. $re = array("{title}", "{excerpt}", "{content}", "{author}", "{short_url}", "{full_url}", "{tags}", "{categories}"); $subst = $wp_subs; if ($post->post_type == 'product') { $p = $product; array_merge($re, $wc_tags); array_merge($subst, $wc_subs); } else { #if it's not a product post then strip out all of the WooCommerce tags $strip_wc = true; } $msg = str_replace($re, $subst, $pattern); if ($strip_wc) { $msg = str_replace($wc_tags, '', $msg); } if ($method == 'photo' && $photo != false) { $r = $nt->channel_photo($ch_name, $msg, $photo); } else { $r = $nt->channel_text($ch_name, $msg); } $publish_date = current_time("mysql", $gmt = 0); if ($r["ok"] == true) { $sending_result = 1; } else { $sending_result = $r["description"]; } $twp_log = $wpdb->get_row("SELECT * FROM {$table_name} WHERE post_id = {$ID}"); if ($twp_log == null) { $wpdb->replace($table_name, array('time' => $publish_date, 'post_id' => $ID, 'sending_result' => $sending_result)); } else { $wpdb->update($table_name, array('time' => $publish_date, 'post_id' => $ID, 'sending_result' => $sending_result), array('post_id' => $ID)); } update_post_meta($ID, '_twp_send_to_channel', 0); //unset($_POST['twp_send_to_channel']); }
/** * Creates a n XML representation of an Order * * @access public * @param mixed $arr * @param $customerNumber * @return mixed */ public function create($arr, $customerNumber) { $orderOptions = get_option('woocommerce_fortnox_order_settings'); $freight_options = get_option('woocommerce_fortnox_freight_settings'); $root = 'Order'; $seq_order_number = get_post_meta($arr->id, '_order_number', true); if (!empty($seq_order_number)) { logthis($seq_order_number); $order['DocumentNumber'] = $seq_order_number; } else { $order['DocumentNumber'] = $arr->id; } $order['AdministrationFee'] = $orderOptions['admin-fee']; $order['OrderDate'] = substr($arr->order_date, 0, 10); $order['DeliveryDate'] = substr($arr->order_date, 0, 10); $order['Currency'] = $arr->get_order_currency(); $order['CurrencyRate'] = '1'; $order['CurrencyUnit'] = '1'; $order['YourOrderNumber'] = $arr->id; $order['CustomerNumber'] = $customerNumber; $order['Address1'] = $arr->billing_address_1; $order['City'] = $arr->billing_city; $order['Country'] = $this->countries[$arr->billing_country]; $order['Phone1'] = $arr->billing_phone; $order['DeliveryAddress1'] = $arr->shipping_address_1; $order['DeliveryCity'] = $arr->shipping_city; $order['DeliveryCountry'] = $this->countries[$arr->shipping_country]; $order['DeliveryZipCode'] = $arr->shipping_postcode; $shipping_methods = $arr->get_shipping_methods(); $shipping_method = reset($shipping_methods); if (!empty($shipping_method)) { if (!empty($shipping_method['method_id'])) { if (isset($freight_options[$shipping_method['method_id']])) { $order['WayOfDelivery'] = $freight_options[$shipping_method['method_id']]; } } } if ($arr->payment_method == 'klarna_checkout') { $order['ExternalInvoiceReference1'] = $arr->id; } if (isset($arr->billing_company) && $arr->billing_company != '') { $order['CustomerName'] = $arr->billing_company; $order['YourReference'] = $arr->billing_first_name . " " . $arr->billing_last_name; } else { $order['CustomerName'] = $arr->billing_first_name . " " . $arr->billing_last_name; $order['DeliveryName'] = $arr->billing_first_name . " " . $arr->billing_last_name; } if ($orderOptions['payment-options'] != '') { $order['TermsOfPayment'] = $orderOptions['payment-options']; } if ($orderOptions['cost-center'] != '') { $order['CostCenter'] = $orderOptions['cost-center']; } $include_freight_tax = get_option('woocommerce_prices_include_tax'); if ($include_freight_tax == 'yes') { $order['Freight'] = $arr->get_total_shipping() * 0.8; } else { $order['Freight'] = $arr->get_total_shipping(); } $order['VATIncluded'] = 'false'; if ($orderOptions['add-payment-type'] == 'on') { $payment_method = get_post_meta($arr->id, '_payment_method_title'); $order['Remarks'] = $payment_method[0]; } $email = array(); $email['EmailAddressTo'] = $arr->billing_email; $order['EmailInformation'] = $email; $invoicerows = array(); //loop all items $index = 0; $pf = new WC_Product_Factory(); foreach ($arr->get_items() as $item) { $key = "OrderRow" . $index; //if variable product there might be a different SKU $is_variation = false; if (empty($item['variation_id'])) { $productId = $item['product_id']; } else { $productId = $item['variation_id']; $is_variation = true; } $product = $pf->get_product($productId); //handles missing product $invoicerow = array(); if (!($product == NULL)) { //!is_null($product) $invoicerow['ArticleNumber'] = $product->get_sku(); } $invoicerow['Description'] = $this->get_item_name($item, $product, $is_variation); $invoicerow['Unit'] = 'st'; $invoicerow['DeliveredQuantity'] = $item['qty']; $invoicerow['OrderedQuantity'] = $item['qty']; $invoicerow['Price'] = $this->get_product_price($item) / $item['qty']; $invoicerow['VAT'] = $this->get_tax_class_by_tax_name($product->get_tax_class(), $arr->shipping_country); $index += 1; $invoicerows[$key] = $invoicerow; } /****HANDLE FEES*****/ foreach ($arr->get_fees() as $item) { $key = "OrderRow" . $index; $invoicerow['Description'] = $item['name']; $invoicerow['Unit'] = 'st'; $invoicerow['DeliveredQuantity'] = 1; $invoicerow['OrderedQuantity'] = 1; $invoicerow['Price'] = $item['line_total']; $invoicerow['VAT'] = 25; $index += 1; $invoicerows[$key] = $invoicerow; } if ($arr->get_total_discount() > 0) { $coupon = $arr->get_used_coupons(); $coupon = new WC_Coupon($coupon[0]); if (!$coupon->apply_before_tax()) { $key = "OrderRow" . $index; $invoicerow = array(); $invoicerow['Description'] = "Rabatt"; $invoicerow['Unit'] = 'st'; $invoicerow['DeliveredQuantity'] = 1; $invoicerow['OrderedQuantity'] = 1; $invoicerow['Price'] = -1 * $arr->get_total_discount(); $invoicerow['VAT'] = 0; $invoicerows[$key] = $invoicerow; $index += 1; } } /****HANDLE PRODUCT AS FREIGHT*****/ if (!empty($orderOptions['freight-product-sku'])) { //RESET FREIGHT $order['Freight'] = 0; $product = $this->get_product_by_sku($orderOptions['freight-product-sku']); $key = "OrderRow" . $index; $invoicerow['ArticleNumber'] = $orderOptions['freight-product-sku']; $invoicerow['Description'] = $product->get_title(); $invoicerow['Unit'] = 'st'; $invoicerow['DeliveredQuantity'] = 1; $invoicerow['OrderedQuantity'] = 1; $invoicerow['Price'] = $arr->get_total_shipping(); $invoicerow['VAT'] = $this->get_tax_class_by_tax_name($product->get_tax_class(), $arr->shipping_country); $invoicerows[$key] = $invoicerow; } $order['OrderRows'] = $invoicerows; logthis(print_r($order, true)); return $this->generate($root, $order); }
function woocommerce_handle_woo_payment($order_id) { global $wpdb; global $woocommerce; $order = new WC_Order($order_id); $items = $order->get_items(); foreach ($items as $item) { $product_name = $item['name']; $product_id = $item['product_id']; $_pf = new WC_Product_Factory(); $_product = $_pf->get_product($product_id); $attributes = $_product->get_attributes(); if (isset($attributes['byt-booking-id'])) { $booking_id = $attributes['byt-booking-id']['value']; $product_terms = wp_get_object_terms($product_id, 'product_cat'); if ($product_terms && count($product_terms) > 0) { if (!is_wp_error($product_terms)) { foreach ($product_terms as $term) { $datasec = array('woo_order_id' => $order_id); if ($term->slug == BOOKYOURTRAVEL_WOO_PRODUCT_CAT_ACCOMMODATIONS) { $wpdb->update(BOOKYOURTRAVEL_ACCOMMODATION_BOOKINGS_TABLE, $datasec, array('Id' => $booking_id)); } else { if ($term->slug == BOOKYOURTRAVEL_WOO_PRODUCT_CAT_TOURS) { $wpdb->update(BOOKYOURTRAVEL_TOUR_BOOKING_TABLE, $datasec, array('Id' => $booking_id)); } else { if ($term->slug == BOOKYOURTRAVEL_WOO_PRODUCT_CAT_CAR_RENTALS) { $wpdb->update(BOOKYOURTRAVEL_CAR_RENTAL_BOOKINGS_TABLE, $datasec, array('Id' => $booking_id)); } else { if ($term->slug == BOOKYOURTRAVEL_WOO_PRODUCT_CAT_CRUISES) { $wpdb->update(BOOKYOURTRAVEL_CRUISE_BOOKINGS_TABLE, $datasec, array('Id' => $booking_id)); } } } } } } } } } }
/** * Adds meta box to product * * @access private * @param $product_id * @return bool */ private function is_product_synced($product_id) { $synced = get_post_meta($product_id, '_is_synced_to_fortnox', true); $pf = new WC_Product_Factory(); $product = $pf->get_product($product_id); if ($product->has_child()) { //sync children $num = count($product->get_children()); $counter = 0; foreach ($product->get_children() as $child_id) { $synced = get_post_meta($child_id, '_is_synced_to_fortnox', true); if ($synced == 1) { $counter++; } } if ($counter == $num) { return true; } else { return false; } } else { if ($synced == 1) { return true; } else { return false; } } }
function check_diff_callback() { global $wpdb; // this is how you get access to the database include_once "class-fortnox3-api.php"; check_ajax_referer('fortnox_woocommerce', 'security'); $pf = new WC_Product_Factory(); $child = $pf->get_product($_POST['product_id']); $sku = $child->get_sku(); $apiInterface = new WCF_API(); $article = $apiInterface->get_article($sku); if ($sku === NULL) { echo json_encode(array('success' => false, 'product_id' => $_POST['product_id'], 'sku' => 'Inget artikelnummer', 'title' => $child->get_title())); } else { if (array_key_exists('Error', $article)) { echo json_encode(array('success' => false, 'product_id' => $_POST['product_id'], 'sku' => $sku, 'title' => $child->get_title())); } else { echo json_encode(array('success' => true, 'product_id' => $_POST['product_id'], 'sku' => $sku, 'title' => $child->get_title())); } } die; // this is required to return a proper result }
/** * * @global type $wpdb * @param type $offer_id * @param type $emails * @since 1.2.0 */ public function ofw_auto_decline_offer($offer_id = null, $emails = null) { global $wpdb; if (isset($_POST["targetID"]) && !empty($_POST["targetID"])) { $post_id = $_POST["targetID"]; } else { $post_id = $offer_id; } if (isset($post_id) && !empty($post_id)) { $post_data = get_post($post_id); $is_offer_buyer_countered_status = $post_data->post_status == 'buyercountered-offer' ? true : false; $table = $wpdb->prefix . "posts"; $data_array = array('post_status' => 'declined-offer', 'post_modified' => date("Y-m-d H:i:s", current_time('timestamp', 0)), 'post_modified_gmt' => date("Y-m-d H:i:s", current_time('timestamp', 1))); $where = array('ID' => $post_id); $wpdb->update($table, $data_array, $where); $post_status_text = __('Declined', $this->plugin_slug); $offer_notes = isset($_POST['angelleye_woocommerce_offer_status_notes']) && $_POST['angelleye_woocommerce_offer_status_notes'] != '' ? $_POST['angelleye_woocommerce_offer_status_notes'] : ''; $recipient = get_post_meta($post_id, 'offer_email', true); $offer_id = $post_id; $offer_uid = get_post_meta($post_id, 'offer_uid', true); $offer_name = get_post_meta($post_id, 'offer_name', true); $offer_email = $recipient; $product_id = get_post_meta($post_id, 'offer_product_id', true); $variant_id = get_post_meta($post_id, 'offer_variation_id', true); $_pf = new WC_Product_Factory(); $product = $variant_id ? $_pf->get_product($variant_id) : $_pf->get_product($product_id); $product_qty = $is_offer_buyer_countered_status ? get_post_meta($post_id, 'offer_buyer_counter_quantity', true) : get_post_meta($post_id, 'offer_quantity', true); $product_price_per = $is_offer_buyer_countered_status ? get_post_meta($post_id, 'offer_buyer_counter_price_per', true) : get_post_meta($post_id, 'offer_price_per', true); $product_total = $product_qty * $product_price_per; if ($is_offer_buyer_countered_status) { update_post_meta($post_id, 'offer_quantity', $product_qty); update_post_meta($post_id, 'offer_price_per', $product_price_per); update_post_meta($post_id, 'offer_amount', $product_total); } $offer_args = array('recipient' => $recipient, 'offer_email' => $offer_email, 'offer_name' => $offer_name, 'offer_id' => $offer_id, 'offer_uid' => $offer_uid, 'product_id' => $product_id, 'product_url' => $product->get_permalink(), 'variant_id' => $variant_id, 'product' => $product, 'product_qty' => $product_qty, 'product_price_per' => $product_price_per, 'product_total' => $product_total, 'offer_notes' => $offer_notes); if ($variant_id) { if ($product->get_sku()) { $identifier = $product->get_sku(); } else { $identifier = '#' . $product->variation_id; } $attributes = $product->get_variation_attributes(); $extra_data = ' – ' . implode(', ', $attributes); $offer_args['product_title_formatted'] = sprintf(__('%s – %s%s', 'woocommerce'), $identifier, $product->get_title(), $extra_data); } else { $offer_args['product_title_formatted'] = $product->get_formatted_name(); } $email_class = 'WC_Declined_Offer_Email'; if (empty($emails)) { $wc_emails = new WC_Emails(); $emails = $wc_emails->get_emails(); } $new_email = $emails[$email_class]; $new_email->recipient = $recipient; $new_email->plugin_slug = $this->plugin_slug; $new_email->template_html = 'woocommerce-offer-declined.php'; $new_email->template_html_path = untrailingslashit(OFW_PLUGIN_URL) . '/admin/includes/emails/'; $new_email->template_plain = 'woocommerce-offer-declined.php'; $new_email->template_plain_path = untrailingslashit(OFW_PLUGIN_URL) . '/admin/includes/emails/plain/'; $new_email->trigger($offer_args); $comment_text = "<span>Updated - Status: </span>"; $comment_text .= $post_status_text; if (isset($offer_notes) && $offer_notes != '') { $comment_text .= '</br>' . nl2br($offer_notes); } $data = array('comment_post_ID' => '', 'comment_author' => 'admin', 'comment_author_email' => '', 'comment_author_url' => '', 'comment_content' => $comment_text, 'comment_type' => '', 'comment_parent' => 0, 'user_id' => get_current_user_id(), 'comment_author_IP' => $_SERVER['REMOTE_ADDR'], 'comment_agent' => '', 'comment_date' => date("Y-m-d H:i:s", current_time('timestamp', 0)), 'comment_approved' => 'post-trashed'); $new_comment_id = wp_insert_comment($data); if ($new_comment_id) { add_comment_meta($new_comment_id, 'angelleye_woocommerce_offer_id', $post_id, true); } } }
/** * Process AJAX request and return quick view popup content * * @since 1.0.0 */ public function ajax_callback() { $nonce = isset($_REQUEST['_wpnonce']) ? esc_attr($_REQUEST['_wpnonce']) : false; if (!wp_verify_nonce($nonce, 'cherry_woocommerce')) { die('Nonce not verifyed'); } $product_id = isset($_REQUEST['product']) ? $_REQUEST['product'] : false; if (!$product_id) { die('Product not found'); } if (!class_exists('WC_Product_Factory')) { die('Product not found'); } global $product, $woocommerce, $post; $product_factory = new WC_Product_Factory(); $post = get_post($product_id); $product = $product_factory->get_product($product_id); setup_postdata($post); cherry_wc_templater()->get_template_part('quick-view'); wp_reset_postdata(); die; }
function pwlp_wishlist_shortcode() { ob_start(); session_start(); $pwlp_genral_dataa = get_option('data_wishlist_genral'); $pwlp_share_dataa = get_option('data_share_wishlist'); $pwlp_style_dataa = get_option('data_style_wishlist'); if (isset($pwlp_genral_dataa) && !empty($pwlp_genral_dataa) || isset($pwlp_share_dataa) && !empty($pwlp_share_dataa) || isset($pwlp_style_dataa) && !empty($pwlp_style_dataa)) { extract($pwlp_genral_dataa); extract($pwlp_share_dataa); extract($pwlp_style_dataa); } if (isset($_GET['add-to-cart'])) { if ($rem_wl == 1) { $prod_id = $_GET['add-to-cart']; $wishlist_data = $_SESSION['wishlist']; foreach ($wishlist_data as $key => $value) { if ($key == $prod_id) { unset($wishlist_data[$key]); $_SESSION['wishlist'] = $wishlist_data; if (is_user_logged_in()) { $pwlp_user_ID = get_current_user_id(); update_user_meta($pwlp_user_ID, '_pwlp_wishlist', $wishlist_data); } } } } } ?> <form class="woocommerce" method="post" action="" id="pwlp_form"> <div class=""> <h2 style="color:<?php echo isset($title_wi_page_col) && !empty($title_wi_page_col) ? $title_wi_page_col : '#141412'; ?> ;"><?php echo $title_wl_page != '' ? $title_wl_page : 'My wishlist on ' . get_bloginfo('name'); ?> </h2> </div> <table class="shop_table cart pwlp_table"> <thead> <tr > <th class="pwl_product-remove"></th> <th class="product-thumbnail"></th> <th class="product-name"> <span class="nobr">Product Name</span> </th> <th class="product-price"> <span class="nobr">Unit Price</span> </th> <th class="product-stock-stauts"> <span class="nobr">Stock Status</span> </th> <th class="product-add-to-cart"></th> </tr> </thead> <tbody> <?php if (isset($_SESSION['wishlist']) && !empty($_SESSION['wishlist'])) { if (is_user_logged_in()) { $pwllp_user_ID = get_current_user_id(); $wishList_data = get_user_meta($pwllp_user_ID, '_pwlp_wishlist'); $wishList_data = $wishList_data[0]; } else { $wishList_data = $_SESSION['wishlist']; } /* echo "<pre>"; echo "user login"; print_r($_SESSION['wishlist']); echo "user_not_login"; print_r($_SESSION['wishlist']); print_r($wishList_data); echo "</pre>"; */ foreach ($wishList_data as $pro_id => $wish_date) { $_pwlp = new WC_Product_Factory(); $pwlp_product = $_pwlp->get_product($pro_id); $pwlp_product->get_availability(); $pur = $pwlp_product->is_purchasable() && $pwlp_product->is_in_stock() ? 'add_to_cart_button' : ''; ?> <tr id="pwlp_product_<?php echo $pro_id; ?> " > <td class="product-remove"> <a class="remove pwlp_remove_id" data-remove-id="<?php echo $pro_id; ?> " >×</a> </td> <td class="product-thumbnail"> <?php $thumbnail = apply_filters('woocommerce_cart_item_thumbnail', $pwlp_product->get_image(), $cart_item, $cart_item_key); if (!$pwlp_product->is_visible()) { echo $thumbnail; } else { printf('<a href="%s">%s</a>', $pwlp_product->get_permalink($cart_item), $thumbnail); } ?> </td> <td class="product-name"> <?php if (!$pwlp_product->is_visible()) { echo apply_filters('woocommerce_cart_item_name', $pwlp_product->get_title(), $cart_item, $cart_item_key) . ' '; } else { echo apply_filters('woocommerce_cart_item_name', sprintf('<a href="%s">%s </a>', $pwlp_product->get_permalink($cart_item), $pwlp_product->get_title()), $cart_item, $cart_item_key); } // Meta data echo WC()->cart->get_item_data($cart_item); // Backorder notification if ($pwlp_product->backorders_require_notification() && $pwlp_product->is_on_backorder($cart_item['quantity'])) { echo '<p class="backorder_notification">' . __('Available on backorder', 'woocommerce') . '</p>'; } ?> </td> <td class="product-price"> <span class="amount"> <?php $pwlp_price = $pwlp_product->price; if (!empty($pwlp_price)) { echo get_woocommerce_currency_symbol(); echo $pwlp_price; } ?> </span> </td> <td class="product-stock-status"> <span class="wishlist-in-stock"><?php echo $pwlp_stock = $pwlp_product->stock_status; ?> </span> </td> <td class="product-add-to-cart"> <?php if (isset($adding_date_wishlist) && $adding_date_wishlist == 1) { ?> <span>Add on :<?php echo $wish_date; ?> </span> <?php } ?> <a href="<?php if (isset($add_to_cart_red)) { echo $add_to_cart_red == 1 ? site_url() . "/cart?add-to-cart=" . $pro_id : $pwlp_product->add_to_cart_url(); } else { echo $pwlp_product->add_to_cart_url(); } ?> " data-product_id="<?php echo $pro_id; ?> " class="pwlp_add_to_cart button <?php echo $pur . ' product_type_' . $product_type; ?> "><?php echo $pwlp_product->add_to_cart_text(); ?> </a> </td> </tr> <?php } } else { ?> <tr> <td colspan="6" class="wishlist-empty" style="text-align:center;"> No products were added to the wishlist </td> </tr> <?php } ?> </tbody> <tfoot> <tr> <td colspan="6"> <?php require_once 'pwlp_share.php'; ?> </td> </tr> </tfoot> </table> </form> <?php }
function hpy_dropdown_variation_attribute_options($args = array()) { $_pf = new WC_Product_Factory(); $args = wp_parse_args(apply_filters('woocommerce_dropdown_variation_attribute_options_args', $args), array('options' => false, 'attribute' => false, 'product' => false, 'selected' => false, 'name' => '', 'id' => '', 'class' => '')); $sortby = get_option('hpy_variant_sort'); $options = $args['options']; $product = $args['product']; $attribute = $args['attribute']; $name = $args['name'] ? $args['name'] : 'attribute_' . sanitize_title($attribute); $id = $args['id'] ? $args['id'] : sanitize_title($attribute); $class = $args['class']; if (empty($options) && !empty($product) && !empty($attribute)) { $attributes = $product->get_variation_attributes(); $options = $attributes[$attribute]; } echo '<select id="' . esc_attr($id) . '" class="' . esc_attr($class) . '" name="' . esc_attr($name) . '" data-attribute_name="attribute_' . esc_attr(sanitize_title($attribute)) . '">'; if ($sortby == 'price-low' || $sortby == 'price-high') { $variantIDs = $product->children['visible']; $variant_list = array(); foreach ($variantIDs as $variants) { $variant_product = $_pf->get_product($variants); $variant_list[] = array($variant_product->get_regular_price() => $variants); } $varcount = count($variant_list); $i = 0; $v = 0; $tmp = array(); while ($i < $varcount) { $keys[] = key($variant_list[$i]); $i++; } if (count(array_unique($keys)) == 1) { if ($product && taxonomy_exists($attribute)) { // Get terms if this is a taxonomy - ordered. We need the names too. $terms = wc_get_product_terms($product->id, $attribute, array('fields' => 'all')); foreach ($terms as $term) { if (in_array($term->slug, $options)) { $clearname = str_replace("-", " ", $term->name); echo '<option value="' . esc_attr($term->slug) . '" ' . selected(sanitize_title($args['selected']), $term->slug, false) . '>' . apply_filters('woocommerce_variation_option_name', $clearname) . '</option>'; } } } else { foreach ($options as $option) { // This handles < 2.4.0 bw compatibility where text attributes were not sanitized. $selected = sanitize_title($args['selected']) === $args['selected'] ? selected($args['selected'], sanitize_title($option), false) : selected($args['selected'], $option, false); $clearname = str_replace("-", " ", $option); echo '<option value="' . esc_attr($option) . '" ' . $selected . '>' . esc_html(apply_filters('woocommerce_variation_option_name', $clearname)) . '</option>'; } } } else { foreach ($variant_list as $list) { $tmp = array_merge($tmp, $list); } if ($sortby == 'price-low') { ksort($tmp); foreach ($tmp as $variant) { $current_variant = get_post_meta($variant); $option = $current_variant['attribute_' . strtolower($attribute)][0]; if ($v == 0) { $selected = ' selected="selected"'; $v++; } else { $selected = ''; } $clearname = str_replace("-", " ", $option); echo '<option value="' . esc_attr($option) . '" ' . $selected . '>' . ucwords(esc_html(apply_filters('woocommerce_variation_option_name', $clearname))) . '</option>'; } } else { if ($sortby == 'price-high') { krsort($tmp); foreach ($tmp as $variant) { $current_variant = get_post_meta($variant); $option = $current_variant['attribute_' . strtolower($attribute)][0]; if ($v == 0) { $selected = ' selected="selected"'; $v++; } else { $selected = ''; } $clearname = str_replace("-", " ", $option); echo '<option value="' . esc_attr($option) . '" ' . $selected . '>' . ucwords(esc_html(apply_filters('woocommerce_variation_option_name', $clearname))) . '</option>'; } } else { if ($product && taxonomy_exists($attribute)) { // Get terms if this is a taxonomy - ordered. We need the names too. $terms = wc_get_product_terms($product->id, $attribute, array('fields' => 'all')); foreach ($terms as $term) { if (in_array($term->slug, $options)) { echo '<option value="' . esc_attr($term->slug) . '" ' . selected(sanitize_title($args['selected']), $term->slug, false) . '>' . apply_filters('woocommerce_variation_option_name', $term->name) . '</option>'; } } } else { foreach ($options as $option) { // This handles < 2.4.0 bw compatibility where text attributes were not sanitized. $selected = sanitize_title($args['selected']) === $args['selected'] ? selected($args['selected'], sanitize_title($option), false) : selected($args['selected'], $option, false); echo '<option value="' . esc_attr($option) . '" ' . $selected . '>' . esc_html(apply_filters('woocommerce_variation_option_name', $option)) . '</option>'; } } } } } } else { if (!empty($options)) { if ($product && taxonomy_exists($attribute)) { // Get terms if this is a taxonomy - ordered. We need the names too. $terms = wc_get_product_terms($product->id, $attribute, array('fields' => 'all')); foreach ($terms as $term) { if (in_array($term->slug, $options)) { echo '<option value="' . esc_attr($term->slug) . '" ' . selected(sanitize_title($args['selected']), $term->slug, false) . '>' . apply_filters('woocommerce_variation_option_name', $term->name) . '</option>'; } } } else { foreach ($options as $option) { // This handles < 2.4.0 bw compatibility where text attributes were not sanitized. $selected = sanitize_title($args['selected']) === $args['selected'] ? selected($args['selected'], sanitize_title($option), false) : selected($args['selected'], $option, false); echo '<option value="' . esc_attr($option) . '" ' . $selected . '>' . esc_html(apply_filters('woocommerce_variation_option_name', $option)) . '</option>'; } } } } echo '</select>'; }
public function authorize($feed, $submission_data, $form, $entry) { $data = array(); $payment_type = $feed["meta"]["pd_payment_type"]; if ($payment_type == "bsb") { $data["customer"]["payment_source"]["type"] = "bsb"; $data["customer"]["payment_source"]["account_name"] = $entry[$feed["meta"]["pd_payment_mapped_details_pd_account_name"]]; $data["customer"]["payment_source"]["account_bsb"] = str_replace('-', '', $entry[$feed["meta"]["pd_payment_mapped_details_pd_account_bsb"]]); $data["customer"]["payment_source"]["account_number"] = $entry[$feed["meta"]["pd_payment_mapped_details_pd_account_number"]]; } else { $data["customer"]["payment_source"]["card_name"] = $submission_data['card_name']; $data["customer"]["payment_source"]["card_number"] = $submission_data['card_number']; $ccdate_array = $submission_data['card_expiration_date']; $ccdate_month = $ccdate_array[0]; if (strlen($ccdate_month) < 2) { $ccdate_month = '0' . $ccdate_month; } $ccdate_year = $ccdate_array[1]; if (strlen($ccdate_year) > 2) { $ccdate_year = substr($ccdate_year, -2); } // Only want last 2 digits $data["customer"]["payment_source"]["expire_month"] = $ccdate_month; $data["customer"]["payment_source"]["expire_year"] = $ccdate_year; $data["customer"]["payment_source"]["card_ccv"] = $submission_data['card_security_code']; } $first_name = $entry[$feed["meta"]["pd_personal_mapped_details_pd_first_name"]]; $last_name = $entry[$feed["meta"]["pd_personal_mapped_details_pd_last_name"]]; $email = $entry[$feed["meta"]["pd_personal_mapped_details_pd_email"]]; $phone = ''; if (!empty($entry[$feed["meta"]["pd_personal_mapped_details_pd_phone"]])) { $phone = str_replace(' ', '', $entry[$feed["meta"]["pd_personal_mapped_details_pd_phone"]]); if (strpos($phone, '0') === 0) { $phone = substr($phone, 1); } if (strpos($phone, '+') === false) { $phone = '+61' . $phone; } } $data["customer"]["payment_source"]["gateway_id"] = $feed["meta"]["pd_select_gateway"]; $data["customer"]["first_name"] = $first_name; $data["customer"]["last_name"] = $last_name; $data["customer"]["email"] = $email; $data["customer"]["phone"] = $phone; $data["customer"]["payment_source"]["address_line1"] = $entry[$feed["meta"]["pd_personal_mapped_details_pd_address_line1"]]; $data["customer"]["payment_source"]["address_line2"] = $entry[$feed["meta"]["pd_personal_mapped_details_pd_address_line2"]]; $data["customer"]["payment_source"]["address_city"] = $entry[$feed["meta"]["pd_personal_mapped_details_pd_address_city"]]; $data["customer"]["payment_source"]["address_state"] = $entry[$feed["meta"]["pd_personal_mapped_details_pd_address_state"]]; $data["customer"]["payment_source"]["address_postcode"] = $entry[$feed["meta"]["pd_personal_mapped_details_pd_address_postcode"]]; $data["customer"]["payment_source"]["address_country"] = $entry[$feed["meta"]["pd_personal_mapped_details_pd_address_country"]]; $data["reference"] = $entry[$feed["meta"]["pd_payment_mapped_details_pd_transaction_reference"]]; $data["description"] = $entry[$feed["meta"]["pd_payment_mapped_details_pd_description"]]; $data["currency"] = !empty($entry[$feed["meta"]["pd_currency"]]) ? $entry[$feed["meta"]["pd_currency"]] : GFCommon::get_currency(); $pd_options = $this->get_plugin_settings(); if ($feed['meta']['pd_send_to_production'] == "1") { $request_token = $pd_options['pd_production_api_key']; $feed_uri = $this->production_endpoint; } else { $request_token = $pd_options['pd_sandbox_api_key']; $feed_uri = $this->sandbox_endpoint; } $feed_gateway_key = $feed['meta']['pd_select_gateway']; $_SESSION['PD_GATEWAY'] = $feed_gateway_key; $start_date = $entry[$feed["meta"]["pd_payment_type_mapped_details_pd_payment_start_date"]]; $transactions = array(); $interval = $entry[$feed["meta"]["pd_payment_type_mapped_details_pd_payment_interval"]]; if (empty($interval)) { $interval = 'one-off'; } $amount_field = $feed["meta"]["pd_total_payable"]; if ($amount_field == 'bb_cart') { if (!empty($_SESSION[BB_CART_SESSION_ITEM])) { $cart_items = $_SESSION[BB_CART_SESSION_ITEM]; if (!empty($cart_items['woo']) && class_exists('WC_Product_Factory')) { // WooCommerce if (!isset($transactions['one-off'])) { $transactions['one-off'] = 0; } foreach ($cart_items['woo'] as $product) { $product_factory = new WC_Product_Factory(); $prod_obj = $product_factory->get_product($product['product_id']); $transactions['one-off'] += $prod_obj->get_price_excluding_tax($product['quantity']); } unset($cart_items['woo']); $transactions['one-off'] += bb_cart_calculate_shipping(); } if (!empty($cart_items['event'])) { // Event Manager Pro if (!isset($transactions['one-off'])) { $transactions['one-off'] = 0; } foreach ($cart_items['event'] as $event) { $transactions['one-off'] += $event['booking']->booking_price; } unset($cart_items['event']); } if (!empty($cart_items)) { // BB Cart foreach ($cart_items as $cart_item) { if (!isset($transactions[$cart_item['frequency']])) { $transactions[$cart_item['frequency']] = 0; } $quantity = !empty($cart_item['quantity']) ? $cart_item['quantity'] : 1; $transactions[$cart_item['frequency']] += $quantity * $cart_item['price'] / 100; } } } } elseif ($amount_field == 'total') { foreach ($form["fields"] as $key => $field) { if ($field['type'] == 'product') { switch ($field['inputType']) { case 'singleproduct': $amount = $this->clean_amount($entry[$field['id'] . '.2']) / 100; break; default: $amount = $this->clean_amount($entry[$field['id']]) / 100; break; } if (!isset($transactions[$interval])) { $transactions[$interval] = 0; } $transactions[$interval] += $amount; } elseif ($field['type'] == 'envoyrecharge') { if (rgpost('input_' . $field['id'] . '_5') == 'recurring') { $ech_interval = rgpost('input_' . $field['id'] . '.2'); } else { $ech_interval = $interval; } if (!isset($transactions[$ech_interval])) { $transactions[$ech_interval] = 0; } $transactions[$ech_interval] += $this->clean_amount($entry[$field['id'] . '.1']) / 100; } elseif ($field['type'] == 'bb_click_array') { if (!isset($transactions[$interval])) { $transactions[$interval] = 0; } $transactions[$interval] += $this->clean_amount($entry[$field['id'] . '.1']) / 100; } } } else { $transactions[$interval] = $this->clean_amount($entry[$amount_field]) / 100; } $total_amount = array_sum($transactions); if ($total_amount <= 0) { $error_message = 'No amounts found to process'; $auth = array('is_authorized' => false, 'transaction_id' => null, 'error_message' => $error_message); $GLOBALS['pd_error'] = $error_message; add_filter('gform_validation_message', array($this, 'change_message'), 10, 2); return $auth; } else { if (!empty($start_date) || strtotime($start_date > time())) { // If start date in future, we don't want to process recurring transactions now $total_amount = $transactions['one-off']; } if ($total_amount > 0) { // Process total amount as a one-off $api_url = $feed_uri . 'charges/'; $data['amount'] = $total_amount; $data_string = json_encode($data); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $api_url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array('x-user-token:' . $request_token, 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string))); $result = curl_exec($ch); curl_close($ch); $response = json_decode($result); $GLOBALS['transaction_id'] = $GLOBALS['pd_error'] = ""; if (!is_object($response) || $response->status > 201 || $response->_code > 250) { if ($response == null || $response == '') { $error_message = __('An unknown error occured. No response was received from the gateway. This is probably a temporary connection issue - please try again.', 'gravityforms-bb-paydock'); } else { if (is_string($response)) { $error_message = __($response, 'gravityforms-bb-paydock'); } elseif (!empty($response->error->message)) { $error_message = __($response->error->message, 'gravityforms-bb-paydock'); } if (property_exists($response->error, 'details')) { if (!is_object($response->error->details[0])) { if (!empty($error_message)) { $error_message .= ': '; } $error_message .= __($response->error->details[0], 'gravityforms-bb-paydock'); } } if (empty($error_message)) { $error_message = __('An unknown error occured. Please try again.', 'gravityforms-bb-paydock'); } } $GLOBALS['pd_error'] = $error_message; add_filter('gform_validation_message', array($this, 'change_message'), 10, 2); // set the form validation to false $auth = array('is_authorized' => false, 'transaction_id' => $response->resource->data->_id, 'error_message' => $error_message); foreach ($form['fields'] as &$field) { if ($field->cssClass == 'pd-show-error') { $field->failed_validation = true; $field->validation_message = 'There was a problem processing your payment. Please try again or contact us.'; break; } } return $auth; } else { $GLOBALS['transaction_id'] = $response->resource->data->_id; $GLOBALS['gateway_transaction_id'] = $response->resource->data->external_id; add_action("gform_entry_created", array($this, "paydock_post_purchase_actions"), 99, 2); $auth = array('is_authorized' => true, 'transaction_id' => $response->resource->data->_id, 'amount' => $total_amount); } } } // Now we can set up subscriptions for any recurring transactions foreach ($transactions as $interval => $amount) { if ($interval == 'one-off' || $amount <= 0) { continue; } $data['amount'] = $amount; // Set the right API endpoint $api_url = $feed_uri . 'subscriptions/'; $frequency = $entry[$feed["meta"]["pd_payment_type_mapped_details_pd_payment_frequency"]]; if (empty($frequency)) { $frequency = 1; } // Hack to support fortnightly recurrence if ($interval == 'fortnight') { $interval = 'week'; $frequency = 2; } $data["schedule"]["frequency"] = $frequency; $data["schedule"]["interval"] = $interval; if (empty($start_date)) { $start_date = date('Y-m-d', strtotime('+' . $frequency . ' ' . $interval)); } $data["schedule"]["start_date"] = $start_date; $end_date = $entry[$feed["meta"]["pd_payment_type_mapped_details_pd_payment_end_date"]]; if ($end_date != "") { $data["schedule"]["end_date"] = $end_date; } $data_string = json_encode($data); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $api_url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array('x-user-token:' . $request_token, 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string))); $result = curl_exec($ch); curl_close($ch); $response = json_decode($result); if (!is_object($response) || $response->status > 201 || $response->_code > 250) { if ($response == null || $response == '') { $error_message = __('An unknown error occured. No response was received from the gateway. This is probably a temporary connection issue - please try again.', 'gravityforms-bb-paydock'); } else { if (is_string($response)) { $error_message = __($response, 'gravityforms-bb-paydock'); } elseif (!empty($response->error->message)) { $error_message = __($response->error->message, 'gravityforms-bb-paydock'); } elseif (property_exists($response->error, 'details')) { if (!is_object($response->error->details[0])) { $error_message = __($response->error->details[0], 'gravityforms-bb-paydock'); } } else { $error_message = __('An unknown error occured. Please try again.', 'gravityforms-bb-paydock'); } } $this->send_subscription_failed_email($first_name, $email, $amount, $interval, $frequency, $error_message); } } return $auth; }
function frontend_box($object, $helpers) { global $evotx, $woocommerce; $txmeta = get_post_custom($object->event_id); // not show event tickets if tickets to show only for loggedin users if (!empty($evotx->evotx_opt['evotx_loggedinuser']) && $evotx->evotx_opt['evotx_loggedinuser'] == 'yes' && !is_user_logged_in()) { return; } if (!empty($txmeta['evotx_tix']) && $txmeta['evotx_tix'][0] == 'yes') { // get options array $woo_product_id = $txmeta['tx_woocommerce_product_id'][0]; $woometa = get_post_custom($woo_product_id); $opt = $helpers['evoOPT2']; ob_start(); ?> <div class='evorow evcal_evdata_row bordb evcal_evrow_sm evo_metarow_tix <?php echo $helpers['end_row_class']; ?> ' data-tx='' data-event_id='<?php echo $object->event_id; ?> ' data-ri='<?php echo $object->repeat_interval; ?> '> <span class='evcal_evdata_icons'><i class='fa <?php echo get_eventON_icon('evcal__evotx_001', 'fa-tags', $helpers['evOPT']); ?> '></i></span> <div class='evcal_evdata_cell'> <h3 class='evo_h3'><?php echo eventon_get_custom_language($opt, 'evoTX_001', 'Ticket Section Title'); ?> </h3> <p class='evo_data_val'><?php echo evo_meta($woometa, '_tx_text'); ?> </p> <?php // ticket image id - if exists $_tix_image_id = !empty($txmeta['_tix_image_id']) ? $txmeta['_tix_image_id'][0] : false; ?> <div class='evoTX_wc <?php echo $_tix_image_id ? 'tximg' : ''; ?> ' data-si='<?php echo !empty($woometa['_sold_individually']) ? $woometa['_sold_individually'][0] : '-'; ?> ' > <div class='evoTX_wc_section'> <?php $_repeat_in_stock = true; $capacity_of_this_repeat = 'none'; // check if capacity managed by repeat intervals of event if (evo_check_yn($txmeta, '_manage_repeat_cap') && evo_check_yn($txmeta, 'evcal_repeat') && !empty($txmeta['repeat_intervals']) && !empty($txmeta['ri_capacity']) && $product->product_type == 'simple') { $ri_capacity = unserialize($txmeta['ri_capacity'][0]); $capacity_of_this_repeat = isset($ri_capacity[$object->repeat_interval]) ? $ri_capacity[$object->repeat_interval] : 0; $_repeat_in_stock = $capacity_of_this_repeat == 0 ? false : true; } // get the woocommerce product $_pf = new WC_Product_Factory(); $product = $_pf->get_product($woo_product_id); if (!$_repeat_in_stock || !empty($woometa['_stock_status']) && $woometa['_stock_status'][0] == 'outofstock') { echo "<p class='evotx_soldout'>" . eventon_get_custom_language($opt, 'evoTX_012', 'Sold Out!') . "</p>"; } else { // SIMPLE product if ($product->product_type == 'simple') { $url = $evotx->addon_data['plugin_path'] . '/templates/template-add-to-cart-single.php'; include $url; } // end simple product // VARIABLE Product if ($product->product_type == 'variable') { include $evotx->addon_data['plugin_path'] . '/templates/template-add-to-cart-variable.php'; } } // is_in_stock() ?> <?php // show remaining tickets or not if ($_repeat_in_stock && evo_check_yn($txmeta, '_show_remain_tix') && evo_check_yn($woometa, '_manage_stock') && !empty($woometa['_stock']) && $woometa['_stock_status'][0] == 'instock' && (!empty($txmeta['remaining_count']) && (int) $txmeta['remaining_count'][0] >= $woometa['_stock'][0] || empty($txmeta['remaining_count'])) && $product->product_type == 'simple') { // get the remaining ticket // count for event // show this remaining total only for simple events $remaining_count = $capacity_of_this_repeat != 'none' ? $capacity_of_this_repeat : $woometa['_stock'][0]; $remaining_count = (int) $remaining_count; echo "<p class='evotx_remaining' data-count='{$remaining_count}'><span>" . $remaining_count . "</span> " . eventon_get_custom_language($opt, 'evoTX_013', 'Tickets remaining!') . "</p>"; } ?> <?php // inquire before buy form include 'html-ticket-inquery.php'; ?> <?php ?> </div><!-- .evoTX_wc_section --> <?php // content for ticket image seciton if ($_tix_image_id) { $img_src = $_tix_image_id ? wp_get_attachment_image_src($_tix_image_id, 'medium') : null; $tix_img_src = !empty($img_src) ? $img_src[0] : null; ?> <div class='evotx_image'> <img src='<?php echo $tix_img_src; ?> '/> <?php if (!empty($txmeta['_tx_img_text'])) { ?> <p class='evotx_caption'><?php echo $txmeta['_tx_img_text'][0]; ?> </p> <?php } ?> </div><div class="clear"></div> <?php } ?> </div> </div> <div class='tx_wc_notic' style='display:none'> <p><b></b><span><?php echo eventon_get_custom_language($opt, 'evoTX_009', 'Successfully added to cart!'); ?> </span> <a class='evcal_btn view_cart' href='<?php echo $woocommerce->cart->get_cart_url(); ?> '><?php echo eventon_get_custom_language($opt, 'evoTX_011', 'View cart'); ?> </a> <a class='evcal_btn checkout' href='<?php echo $woocommerce->cart->get_checkout_url(); ?> '><?php echo eventon_get_custom_language($opt, 'evoTX_010', 'Checkout'); ?> </a><em></em></p> </div> <?php echo $helpers['end']; ?> </div> <?php $output = ob_get_clean(); return $output; } }
/** * Add offer to cart * @since 0.1.0 */ protected function add_offer_to_cart($offer = array(), $offer_meta = array()) { if (!is_admin()) { global $woocommerce; $quantity = $offer_meta['offer_quantity'][0]; $product_id = $offer_meta['orig_offer_product_id'][0]; $product_variation_id = $offer_meta['orig_offer_variation_id'][0]; $_pf = new WC_Product_Factory(); $_pf = new WC_Product_Factory(); $_product = $product_variation_id ? $_pf->get_product($product_variation_id) : $_pf->get_product($product_id); $_product_stock = $_product->get_total_stock(); // lookup product meta by id or variant id if ($product_variation_id) { $product_variation_data = $_product->get_variation_attributes(); } $product_variation_data['Offer ID'] = $offer->ID; $product_meta['woocommerce_offer_id'] = $offer->ID; $product_meta['woocommerce_offer_quantity'] = $offer_meta['offer_quantity'][0]; $product_meta['woocommerce_offer_price_per'] = $offer_meta['offer_price_per'][0]; $found = false; foreach ($woocommerce->cart->get_cart() as $cart_item) { // check if offer id already in cart if (isset($cart_item['woocommerce_offer_id']) && $cart_item['woocommerce_offer_id'] == $offer->ID) { $found = true; $message = sprintf('<a href="%s" class="button wc-forward">%s</a> %s', $woocommerce->cart->get_cart_url(), __('View Cart', 'woocommerce'), __('Offer already added to cart', $this->plugin_slug)); $this->send_api_response($message); } } if (!$found) { $item_id = $woocommerce->cart->add_to_cart($product_id, $quantity, $product_variation_id, $product_variation_data, $product_meta); } if (isset($item_id)) { return true; } } return false; }
<h1 class="entry-title" style="border-bottom:none;"><?php the_title(); ?> </h1> </header> <?php /* * ***** To get all womens post start ** */ $args = array('post_type' => 'product', 'numberposts' => -1); query_posts($args); /* * ***** To get all womens post end ** */ while (have_posts()) { the_post(); global $woocommerce, $product; $_pf = new WC_Product_Factory(); $_product = $_pf->get_product(get_the_ID()); ?> <div class="col-md-3"> <div class="product-box"> <a href="<?php the_permalink(); ?> "><img src="<?php echo wp_get_attachment_url(get_post_thumbnail_id(get_the_ID())); ?> "></a> <a href="<?php the_permalink(); ?>
new AlgoliaPlugin(); new AlgoliaPluginAuto(); /** * Variables Definition */ $batch_count = 100; $attributesToSnippet = array("content"); /** * Defaults Variables */ $attributesToIndex = array("title", "excerpt", "content", "author", "type"); /** Woo Commerce Handling */ add_filter('prepare_algolia_record', function ($data) { if (class_exists('WC_Product_Factory') && $data->type == 'product') { $algolia_registry = \Algolia\Core\Registry::getInstance(); $factory = new WC_Product_Factory(); $product = $factory->get_product($data->objectID); $product_attrs = array('virtual' => $product->is_virtual(), 'sku' => $product->get_sku(), 'taxable' => $product->is_taxable(), 'tax_status' => $product->get_tax_status(), 'tax_class' => $product->get_tax_class(), 'managing_stock' => $product->managing_stock(), 'stock_quantity' => (int) $product->get_stock_quantity(), 'in_stock' => $product->is_in_stock(), 'backorders_allowed' => $product->backorders_allowed(), 'sold_individually' => $product->is_sold_individually(), 'purchaseable' => $product->is_purchasable(), 'visible' => $product->is_visible(), 'catalog_visibility' => $product->visibility, 'on_sale' => $product->is_on_sale(), 'weight' => $product->get_weight() ? wc_format_decimal($product->get_weight(), 2) : null, 'length' => $product->length, 'shipping_required' => $product->needs_shipping(), 'shipping_taxable' => $product->is_shipping_taxable(), 'shipping_class' => $product->get_shipping_class(), 'shipping_class_id' => 0 !== $product->get_shipping_class_id() ? $product->get_shipping_class_id() : null, 'reviews_allowed' => 'open' === $product->get_post_data()->comment_status, 'average_rating' => wc_format_decimal($product->get_average_rating(), 2), 'rating_count' => (int) $product->get_rating_count(), 'related_ids' => array_map('absint', array_values($product->get_related())), 'upsell_ids' => array_map('absint', $product->get_upsells()), 'download_type' => $product->download_type, 'purchase_note' => wpautop(do_shortcode(wp_kses_post($product->purchase_note)))); foreach ($product_attrs as $key => $value) { if (in_array($key, array_keys($algolia_registry->metas[$data->type]))) { if ($algolia_registry->metas[$data->type][$key]["indexable"]) { $data->{$key} = \Algolia\Core\WordpressFetcher::try_cast($value); } } } foreach ($product->get_attributes() as $attribute) { if (in_array($attribute['name'], array_keys($algolia_registry->metas[$data->type]))) { if ($algolia_registry->metas[$data->type][$attribute['name']]["indexable"]) { $product_attrs[$attribute['name']] = \Algolia\Core\WordpressFetcher::try_cast($attribute['value']); } }
public function addOfferNoteCallback() { if (is_admin() && (defined('DOING_AJAX') || DOING_AJAX)) { $post_id = $_POST["targetID"]; // Get current data for Offer $post_data = get_post($post_id); // Filter Post Status Label $post_status_text = strtolower($post_data->post_status) == 'publish' ? 'Pending' : $post_data->post_status; $post_status_text = ucwords(str_replace("-", " ", str_replace("offer", " ", strtolower($post_status_text)))); $noteSendToBuyer = isset($_POST["noteSendToBuyer"]) && $_POST["noteSendToBuyer"] != '' ? '1' : ''; $offer_notes = $_POST['noteContent']; $current_user = wp_get_current_user(); // Insert WP comment $comment_text = "<span>" . __('Offer Note:', $this->plugin_slug) . "</span>"; if ($noteSendToBuyer != '1') { $comment_text .= " " . __('(admin only)', $this->plugin_slug); } else { $comment_text .= " " . __('(sent to buyer)', $this->plugin_slug); } $comment_text .= "<br />" . $offer_notes; $data = array('comment_post_ID' => '', 'comment_author' => $current_user->user_login, 'comment_author_email' => $current_user->user_email, 'comment_author_url' => '', 'comment_content' => $comment_text, 'comment_type' => '', 'comment_parent' => 0, 'user_id' => get_current_user_id(), 'comment_author_IP' => $_SERVER['REMOTE_ADDR'], 'comment_agent' => '', 'comment_date' => date("Y-m-d H:i:s", current_time('timestamp', 0)), 'comment_approved' => 'post-trashed'); $new_comment_id = wp_insert_comment($data); // insert comment meta if ($new_comment_id) { add_comment_meta($new_comment_id, 'angelleye_woocommerce_offer_id', $post_id, true); } if ($new_comment_id) { if ($noteSendToBuyer == '1') { // Email buyer the offer note (not private admin note) /** * Offer note email template * @since 0.1.0 */ // set recipient email $recipient = get_post_meta($post_id, 'offer_email', true); $offer_id = $post_id; $offer_uid = get_post_meta($post_id, 'offer_uid', true); $offer_name = get_post_meta($post_id, 'offer_name', true); $offer_email = $recipient; $product_id = get_post_meta($post_id, 'offer_product_id', true); $variant_id = get_post_meta($post_id, 'offer_variation_id', true); $_pf = new WC_Product_Factory(); $product = $variant_id ? $_pf->get_product($variant_id) : $_pf->get_product($product_id); // if buyercountered-offer previous then use buyer counter values $is_offer_buyer_countered_status = $post_data->post_status == 'buyercountered-offer' ? true : false; $product_qty = $is_offer_buyer_countered_status ? get_post_meta($post_id, 'offer_buyer_counter_quantity', true) : get_post_meta($post_id, 'offer_quantity', true); $product_price_per = $is_offer_buyer_countered_status ? get_post_meta($post_id, 'offer_buyer_counter_price_per', true) : get_post_meta($post_id, 'offer_price_per', true); $product_total = $product_qty * $product_price_per; $offer_args = array('recipient' => $recipient, 'offer_email' => $offer_email, 'offer_name' => $offer_name, 'offer_id' => $offer_id, 'offer_uid' => $offer_uid, 'product_id' => $product_id, 'product_url' => $product->get_permalink(), 'variant_id' => $variant_id, 'product' => $product, 'product_qty' => $product_qty, 'product_price_per' => $product_price_per, 'product_total' => $product_total, 'offer_notes' => $offer_notes); if ($variant_id) { if ($product->get_sku()) { $identifier = $product->get_sku(); } else { $identifier = '#' . $product->variation_id; } $attributes = $product->get_variation_attributes(); $extra_data = ' – ' . implode(', ', $attributes); $offer_args['product_title_formatted'] = sprintf(__('%s – %s%s', 'woocommerce'), $identifier, $product->get_title(), $extra_data); } else { $offer_args['product_title_formatted'] = $product->get_formatted_name(); } // the email we want to send $email_class = 'WC_Offer_Note_Email'; // load the WooCommerce Emails $wc_emails = new WC_Emails(); $emails = $wc_emails->get_emails(); // select the email we want & trigger it to send $new_email = $emails[$email_class]; $new_email->recipient = $recipient; // set plugin slug in email class $new_email->plugin_slug = $this->plugin_slug; // define email template/path (html) $new_email->template_html = 'woocommerce-offer-note.php'; $new_email->template_html_path = plugin_dir_path(__FILE__) . 'includes/emails/'; // define email template/path (plain) $new_email->template_plain = 'woocommerce-offer-note.php'; $new_email->template_plain_path = plugin_dir_path(__FILE__) . 'includes/emails/plain/'; $new_email->trigger($offer_args); } $redirect_url = admin_url('post.php?post=' . $post_id . '&action=edit&noheader=true&message=11'); echo $redirect_url; } else { echo 'failed'; } die; // this is required to return a proper result } }
/** * form shortcode of variation fields for product * * Note : those will be different for rods and lures so we create an overwrite ot the template */ function pierry_show_variation_attributes() { global $post; $_pf = new WC_Product_Factory(); $product = $_pf->get_product($post->ID); $field_desc = pierry_variation_fields_get_available_fields(); $fields = pierry_variation_fields_get($post->ID); $attributes = $attributes = $product->get_attributes(); $categories = majorcraft_get_all_categories($post->ID); //if(in_array('lures', $categories)) { $variation_attributes = array('columns' => 2, 'fields' => array('is_in_stock' => 'Status')); foreach ($attributes as $attribute) { if ($attribute['is_visible']) { $variation_attributes['fields']['attribute_' . $attribute['name']] = wc_attribute_label($attribute['name']); } } foreach ($fields as $slug => $f) { $intersection = array_intersect(array_keys($categories), array_values($field_desc[$slug]->cats)); if (!empty($intersection)) { $variation_attributes['fields'][$slug] = $field_desc[$slug]->name; } } /*} else if(in_array('rods', $categories)) { }*/ $i = 0; $shortcode = '[pierry_variation_attrbutes columns="' . $variation_attributes['columns'] . '"'; if (!empty($variation_attributes['fields']) && is_array($variation_attributes['fields'])) { $shortcode .= ' fields="'; foreach ($variation_attributes['fields'] as $slug => $name) { if ($i > 0) { $shortcode .= ';'; } $shortcode .= $slug . '=>' . $name . ":"; $i++; } } $shortcode .= '"]'; echo do_shortcode($shortcode); }
public static function addCustomDataToProduct($cart_item_data, $product_id, $variation_id) { global $woocommerce; $_pf = new WC_Product_Factory(); $data = $_POST; // Split all the products added to the cart $unique_cart_item_key = md5(microtime() . rand() . "Hi Mom!"); $cart_item_data['unique_key'] = $unique_cart_item_key; $product = $_pf->get_product($product_id); if (TauchTerminal_Tulamben::isRoomProduct($product->get_sku())) { $cart_item_data['start_date'] = $data['start']; $cart_item_data['end_date'] = $data['end']; $attributes = $product->get_attributes(); if ($data['quantity-person']) { $cart_item_data['persons'] = $data['quantity-person']; } if ($data['attribute_bed']) { $labels = self::getAttributeLabel($attributes, 'attribute_bed', $data['attribute_bed']); $name = $labels['name']; $cart_item_data['ttt_meta'][$name] = $labels['value']; } if ($data['attribute_special-requests']) { $labels = self::getAttributeLabel($attributes, 'attribute_special-requests', $data['attribute_special-requests']); $name = $labels['name']; $cart_item_data['ttt_meta'][$name] = $labels['value']; } } return $cart_item_data; }
function enquiryform($atts, $content = "") { global $woocommerce, $product; if (isset($_POST['en_submit'])) { $insert_enquiry = array('post_title' => $_POST['en_name'], 'post_content' => $_POST['en_notes'], 'post_status' => 'publish', 'post_author' => 1, 'post_type' => 'enquiry'); // Insert the post into the database $enquiry_id = wp_insert_post($insert_enquiry); global $wc; $en_product = array(); if ($enquiry_id) { update_post_meta($enquiry_id, "_enquiry_item", $en_product); update_post_meta($enquiry_id, "_enquiry_email", $_POST['en_email']); update_post_meta($enquiry_id, "_enquiry_phone", $_POST['en_phone']); update_post_meta($enquiry_id, "_enquiry_postcode", $_POST['en_postcode']); update_post_meta($enquiry_id, "_enquiry_address", $_POST['en_address']); $rand_order_id = rand(0, 1321321); update_post_meta($enquiry_id, "_enquiry_total_amt", WC()->cart->get_total()); update_post_meta($enquiry_id, "_enquiry_sub_total", WC()->cart->get_cart_subtotal()); } add_filter('wp_mail_content_type', 'set_html_content_type'); //echo $file_save_path; $admin_email = get_option('admin_email'); //$admin_email ="*****@*****.**"; $attachments = array($file_save_path); //$headers = "From: Chadder ". "\r\n"; $headers = 'From: Drizzconnection <' . $admin_email . '>' . "\r\n"; $subject = "Product Enquiry"; $message .= ""; $message .= "<p>Hi Admin,</p>"; $message .= "<p>" . $_POST['en_name'] . " has sent product enquiry .<p>"; $message .= "<h3 class='od-info'>Customer Information</h3>"; $message .= "<table border='1' cellpadding='5' cellspacing='0'>"; $message .= "<tr><td>Name :</td><td>" . $_POST['en_name'] . "</td></tr>"; $message .= "<tr><td>Email: </td><td>" . $_POST['en_email'] . "</td></tr>"; $message .= "<tr><td>Phone: </td><td>" . $_POST['en_phone'] . "</td></tr>"; $message .= "<tr><td>Postcode: </td><td>" . $_POST['en_postcode'] . "</td></tr>"; $message .= "<tr><td>Address: </td><td>" . $_POST['en_address'] . "</td></tr>"; $message .= "</table>"; $message .= "<br/><h3 class='od-info'>Order Information</h3>"; $message .= "<table border='1' cellpadding='5' cellspacing='0'>"; //$message .= "<tr><td>Hi,</td></tr>"; //$message .= "<tr><td>".$_POST['en_name']." has sent product enquiry .Please find the attchement</td></tr>"; $message .= "<tr><th>Product name</th><th>Variations</th><th>Price</th><th>Qty</th><th>Total</th></tr>"; foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) { $var_array = $cart_item['variation']; $att_html = ""; foreach ($var_array as $key => $value) { $att = explode("_", $key); $att_name = $att[1]; $att_value = $value; $att_html .= $att_name . ":" . $att_value . "<br/>"; } $_pf = new WC_Product_Factory(); $_product = $_pf->get_product($cart_item['product_id']); $product_quantity = $cart_item['quantity']; $message .= "<tr><td>" . get_the_title($cart_item['product_id']) . "</td><td>" . $att_html . "</td><th>" . apply_filters('woocommerce_cart_item_price', WC()->cart->get_product_price($_product), $cart_item, $cart_item_key) . "</th>\n\t <th>" . $product_quantity . "</th><th>" . $cart_item['line_total'] . "</th></tr>"; } $message .= "<tr><td colspan='4'>Total:</td><td>" . WC()->cart->get_total() . "</td></tr>"; $message .= "</table>"; //$message .="<p>Total:".WC()->cart->get_total()."</p>"; //echo $message;break; $ret = wp_mail($admin_email, $subject, $message, $headers); remove_filter('wp_mail_content_type', 'set_html_content_type'); $thankyou_link = ot_get_option('enquiry_thank_you_page'); $redirect = get_permalink($thankyou_link); global $woocommerce; $woocommerce->cart->empty_cart(); wp_safe_redirect($redirect); exit; } ob_start(); ?> <form action="<?php echo get_permalink(); ?> " method="POST" name="enquiry_form" id="enquiry_form"> <?php if (isset($_POST['en_submit'])) { ?> <?php ?> <?php } ?> <div class="woocommerce-billing-fields"> <h3>Enquiry Form</h3> <p class="form-row form-row "> <label>Name</label><input name="en_name" id="en_name" type="text" required="required"></p> <p class="form-row form-row "><label>Address</label><textarea name="en_address" required="required" cols="25" rows="25"></textarea></p> <p class="form-row form-row "><label>Post code</label><input name="en_postcode" id="en_postcode" type="text" required="required"></p> <p class="form-row form-row"><label>Email</label><input name="en_email" id="en_email" type="text" required="required"> </p> <p style="display:none;" id="email_valid"><label> </label><span style="font-size:15px;color:#FF0000">Invalid email address</span></p> <p class="form-row form-row"><label>Telephone</label><input name="en_phone" id="en_phone" type="text" required="required"></p> <p class="form-row form-row"> <label>Notes</label><textarea name="en_notes" required="required" cols="25" rows="25"></textarea></p> <p><input type="submit" class="enq-subt" name="en_submit" value="Send Enquiry"></p> </form> </div> <?php $s = ob_get_contents(); ob_clean(); return $s; }