Skip to content

Instantly share code, notes, and snippets.

@hssktm
Last active October 28, 2024 11:41
Show Gist options
  • Save hssktm/e8c49ec37565050613e96aee1226304a to your computer and use it in GitHub Desktop.
Save hssktm/e8c49ec37565050613e96aee1226304a to your computer and use it in GitHub Desktop.
Extract different woocommerce fields easily
function woo_field($property) {
$date_format = 'd - M - Y'; // Format Date
$info = null;
if (!in_array($property, ['cart_product_ids', 'cart_total_items', 'cart_total_price'])) {
global $product;
if (!$product) {
$product = wc_get_product(get_the_ID());
}
if (!$product) {
return "This is not a product";
}
// Cases that depend on a product
switch ($property) {
case 'id': // Extracts the product ID
$info = $product->get_id();
break;
case 'type': // Extracts the product type
$info = $product->get_type();
break;
case 'name': // Extracts the product name
$info = $product->get_name();
break;
case 'slug': // Extracts the product slug
$info = $product->get_slug();
break;
case 'date_created': // Formats the creation date of the product
$info = date_i18n($date_format, strtotime($product->get_date_created()->date('Y-m-d')));
break;
case 'date_modified': // Formats the modification date of the product
$info = date_i18n($date_format, strtotime($product->get_date_modified()->date('Y-m-d')));
break;
case 'status': // Extracts the product status
$info = $product->get_status();
break;
case 'featured': // Extracts if the product is featured and converts it to 'yes' or 'no'
$featured = $product->get_featured();
$info = $featured ? 'yes' : 'no';
break;
case 'catalog_visibility': // Extracts the product catalog visibility
$info = $product->get_catalog_visibility();
break;
case 'description': // Extracts the product description
$info = $product->get_description();
break;
case 'short_description': // Extracts the product short description
$info = $product->get_short_description();
break;
case 'sku': // Extracts the product SKU
$info = $product->get_sku();
break;
case 'menu_order': // Extracts the product menu order
$info = $product->get_menu_order();
break;
case 'virtual': // Extracts if the product is virtual and converts it to 'yes' or 'no'
$virtual = $product->get_virtual();
$info = $virtual ? 'yes' : 'no';
break;
case 'price': // Extract the price
$price = $product->get_price();
if (is_numeric($price)) {
$tax_display_mode = get_option('woocommerce_tax_display_shop');
if ($tax_display_mode === 'incl') {
$price_with_tax = wc_get_price_including_tax($product);
$info = get_woocommerce_currency_symbol() . number_format($price_with_tax, 2);
} else {
$price_excl_tax = wc_get_price_excluding_tax($product);
$info = get_woocommerce_currency_symbol() . number_format($price_excl_tax, 2);
}
} else {
$info = null;
}
break;
case 'regular_price': // Extract the regular price
$regular_price = $product->get_regular_price();
if (is_numeric($regular_price)) {
$tax_display_mode = get_option('woocommerce_tax_display_shop');
if ($tax_display_mode === 'incl') {
$regular_price_with_tax = wc_get_price_including_tax($product, array('price' => $regular_price));
$info = get_woocommerce_currency_symbol() . number_format($regular_price_with_tax, 2);
} else {
$regular_price_excl_tax = wc_get_price_excluding_tax($product, array('price' => $regular_price));
$info = get_woocommerce_currency_symbol() . number_format($regular_price_excl_tax, 2);
}
} else {
$info = null;
}
break;
case 'sale_price': // Extract the sale price
$sale_price = $product->get_sale_price();
if (is_numeric($sale_price)) {
$tax_display_mode = get_option('woocommerce_tax_display_shop');
if ($tax_display_mode === 'incl') {
$sale_price_with_tax = wc_get_price_including_tax($product, array('price' => $sale_price));
$info = get_woocommerce_currency_symbol() . number_format($sale_price_with_tax, 2);
} else {
$sale_price_excl_tax = wc_get_price_excluding_tax($product, array('price' => $sale_price));
$info = get_woocommerce_currency_symbol() . number_format($sale_price_excl_tax, 2);
}
} else {
$info = null;
}
break;
case 'tax_suffix': // Extract the tax suffix
$suffix = get_option('woocommerce_price_display_suffix');
if ($suffix) {
$price_including_tax = wc_get_price_including_tax($product);
$price_excluding_tax = wc_get_price_excluding_tax($product);
$suffix = str_replace('{price_including_tax}', get_woocommerce_currency_symbol() . number_format($price_including_tax, 2), $suffix);
$suffix = str_replace('{price_excluding_tax}', get_woocommerce_currency_symbol() . number_format($price_excluding_tax, 2), $suffix);
}
$info = $suffix ? $suffix : '';
break;
case 'tax_included': // Check if tax is included
$tax_included = get_option('woocommerce_tax_display_shop') === 'incl' ? 'yes' : 'no';
$info = $tax_included;
break;
case 'price_tax_included': // Extract the price including tax
$price = $product->get_price();
if (is_numeric($price)) {
$price_including_tax = wc_get_price_including_tax($product, array('price' => $price));
$info = get_woocommerce_currency_symbol() . number_format($price_including_tax, 2);
} else {
$info = null;
}
break;
case 'price_tax_excluding': // Extract the price excluding tax
$price = $product->get_price();
if (is_numeric($price)) {
$price_excluding_tax = wc_get_price_excluding_tax($product, array('price' => $price));
$info = get_woocommerce_currency_symbol() . number_format($price_excluding_tax, 2);
} else {
$info = null;
}
break;
case 'find_variable_price': // Check if the current product is a variable product
$prices = [];
if ($product->is_type('variable')) {
$variations = $product->get_available_variations();
foreach ($variations as $variation) {
$prices[] = $variation['display_price'];
}
} elseif ($product->is_type('grouped')) {
$children = $product->get_children();
foreach ($children as $child_id) {
$child_product = wc_get_product($child_id);
if ($child_product) {
$prices[] = $child_product->get_price();
}
}
}
$info = (count(array_unique($prices)) > 1) ? 'yes' : 'no';
break;
case 'is_on_sale': // Verifies if the product is on sale
$is_on_sale = $product->is_on_sale();
$info = $is_on_sale ? 'yes' : 'no';
break;
case 'date_on_sale_from': //Extract sale start date
$date_on_sale_from = $product->get_date_on_sale_from();
if (!empty($date_on_sale_from)) {
$formatted_date = date_i18n($date_format, strtotime($date_on_sale_from));
$info = $formatted_date;
} else {
$info = null;
}
break;
case 'date_on_sale_to': //Extract sale expiration date
$info = $product->get_date_on_sale_to();
if (!empty($info)) {
$formatted_date = date_i18n($date_format, strtotime($info));
$info = $formatted_date;
} else {
$info = null;
}
break;
case 'date_on_sale_to_year': // Extraer año de expiración de venta
$date_on_sale_to = null;
if ($product->is_type('variable')) {
$children_ids = $product->get_children();
if (!empty($children_ids)) {
$first_child_id = reset($children_ids);
$first_child = wc_get_product($first_child_id);
$date_on_sale_to = $first_child->get_date_on_sale_to();
}
} else {
$date_on_sale_to = $product->get_date_on_sale_to();
}
if (!empty($date_on_sale_to)) {
$info = date_i18n('Y', strtotime($date_on_sale_to));
} else {
$info = null;
}
break;
case 'date_on_sale_to_month': // Extraer mes de expiración de venta
$date_on_sale_to = null;
if ($product->is_type('variable')) {
$children_ids = $product->get_children();
if (!empty($children_ids)) {
$first_child_id = reset($children_ids);
$first_child = wc_get_product($first_child_id);
$date_on_sale_to = $first_child->get_date_on_sale_to();
}
} else {
$date_on_sale_to = $product->get_date_on_sale_to();
}
if (!empty($date_on_sale_to)) {
$info = date_i18n('m', strtotime($date_on_sale_to));
} else {
$info = null;
}
break;
case 'date_on_sale_to_day': // Extraer día de expiración de venta
$date_on_sale_to = null;
if ($product->is_type('variable')) {
$children_ids = $product->get_children();
if (!empty($children_ids)) {
$first_child_id = reset($children_ids);
$first_child = wc_get_product($first_child_id);
$date_on_sale_to = $first_child->get_date_on_sale_to();
}
} else {
$date_on_sale_to = $product->get_date_on_sale_to();
}
if (!empty($date_on_sale_to)) {
$info = date_i18n('d', strtotime($date_on_sale_to));
} else {
$info = null;
}
break;
case 'discount_percentage': // Calculate the discount percentage
$regular_price = $product->get_regular_price();
$sale_price = $product->get_sale_price();
if (is_numeric($regular_price) && is_numeric($sale_price) && $regular_price > 0) {
$discount_percentage = round((($regular_price - $sale_price) / $regular_price) * 100);
$info = '-'. $discount_percentage . '%';
} else {
$info = null;
}
break;
case 'discount_amount': // Calculate the discount amount in money
$regular_price = $product->get_regular_price();
$sale_price = $product->get_sale_price();
if (is_numeric($regular_price) && is_numeric($sale_price) && $regular_price > 0) {
$tax_display_mode = get_option('woocommerce_tax_display_shop');
if ($tax_display_mode === 'incl') {
$regular_price_including_tax = wc_get_price_including_tax($product, array('price' => $regular_price));
$sale_price_including_tax = wc_get_price_including_tax($product, array('price' => $sale_price));
$discount_amount = $regular_price_including_tax - $sale_price_including_tax;
} else {
$regular_price_excluding_tax = wc_get_price_excluding_tax($product, array('price' => $regular_price));
$sale_price_excluding_tax = wc_get_price_excluding_tax($product, array('price' => $sale_price));
$discount_amount = $regular_price_excluding_tax - $sale_price_excluding_tax;
}
$info = get_woocommerce_currency_symbol() . number_format($discount_amount, 2);
} else {
$info = null;
}
break;
case 'total_sales': // Extracts the total sales of the product
$info = $product->get_total_sales();
break;
case 'tax_status': // Extracts the tax status of the product
$info = $product->get_tax_status();
break;
case 'tax_class': // Extracts the tax class of the product
$info = $product->get_tax_class();
break;
case 'manage_stock': // Extracts if the product manages stock and converts it to 'yes' or 'no'
$manage_stock = $product->get_manage_stock();
$info = $manage_stock ? 'yes' : 'no';
break;
case 'stock_quantity': // Extracts the stock quantity of the product
$info = $product->get_stock_quantity();
break;
case 'stock_status': // Extracts the stock status of the product
$info = $product->get_stock_status();
break;
case 'backorders': // Extracts the backorder status of the product
$info = $product->get_backorders();
break;
case 'sold_individually': // Extracts if the product is sold individually
$info = $product->get_sold_individually();
break;
case 'purchase_note': // Extracts the purchase note of the product
$info = $product->get_purchase_note();
break;
case 'shipping_class_id': // Extracts the shipping class ID of the product
$info = $product->get_shipping_class_id();
break;
case 'weight': // Extracts the weight of the product
$info = $product->get_weight() . ' ' . get_option('woocommerce_weight_unit');
break;
case 'length': // Extracts the length of the product
$info = $product->get_length() . ' ' . get_option('woocommerce_dimension_unit');
break;
case 'width': // Extracts the width of the product
$info = $product->get_width() . ' ' . get_option('woocommerce_dimension_unit');
break;
case 'height': // Extracts the height of the product
$info = $product->get_height() . ' ' . get_option('woocommerce_dimension_unit');
break;
case 'dimensions': // Extracts the dimensions (length, width, and height) of the product
$info = $product->get_dimensions();
break;
case 'upsell_ids': // Extracts the upsell product IDs of the product
$upsell_ids = implode(',', $product->get_upsell_ids());
$info = $upsell_ids !== '' ? $upsell_ids : 'none';
break;
case 'cross_sell_ids': // Extracts the cross-sell product IDs of the product
$cross_sell_ids = implode(',', $product->get_cross_sell_ids());
$info = $cross_sell_ids !== '' ? $cross_sell_ids : 'none';
break;
case 'parent_id': // Extracts the parent product ID of the product
$info = $product->get_parent_id();
break;
case 'children': // Extracts the child product IDs (variations) of the product
$children_ids = implode(', ', $product->get_children());
$info = $children_ids !== '' ? $children_ids : 'none';
break;
case 'children_names': // Extracts the attribute names of the child products (variations) of the product
$children_names = array();
$children_ids = $product->get_children();
foreach ($children_ids as $child_id) {
$variation = wc_get_product($child_id);
$attributes = $variation->get_attributes();
foreach ($attributes as $attribute_name => $attribute) {
$term_name = $attribute;
if (!empty($term_name)) {
$children_names[] = $term_name;
} else {
$children_names[] = 'No Name Found';
}
}
}
$info = implode(', ', $children_names);
$info = $info !== '' ? $info : 'none';
break;
case 'attributes': // Extracts the attributes of the product
$attributes = $product->get_attributes();
$attribute_names = array();
foreach ($attributes as $attribute) {
$attribute_names[] = $attribute['name'];
}
$info = implode(', ', $attribute_names);
$info = $info !== '' ? $info : 'none';
break;
case 'default_attributes': // Extracts the default attributes of the product
$default_attributes = $product->get_default_attributes();
$default_values = array();
foreach ($default_attributes as $attribute_name => $attribute_value) {
$term_name = get_term_by('slug', $attribute_value, $attribute_name)->name;
$default_values[] = $term_name;
}
$info = implode(', ', $default_values);
$info = $info !== '' ? $info : 'none';
break;
case 'attribute': // Extracts a specific attribute value of the product
$info = $product->get_attribute('attributeid');
break;
case 'category_ids': // Extracts the category IDs of the product
$category_ids = $product->get_category_ids();
$info = implode(',', $category_ids);
break;
case 'tag_ids': // Extracts the tag IDs of the product
$tag_ids = $product->get_tag_ids();
$info = implode(',', $tag_ids);
break;
case 'downloads': // Extracts the downloads of the product
$downloads = $product->get_downloads();
$info = json_encode($downloads);
break;
case 'download_expiry': // Extracts the download expiry of the product
$info = $product->get_download_expiry();
break;
case 'downloadable': // Extracts if the product is downloadable
$downloadable = $product->get_downloadable();
$info = $downloadable ? 'yes' : 'no';
break;
case 'download_limit': // Extracts the download limit of the product
$download_limit = $product->get_download_limit();
$info = ($download_limit !== -1 && !empty($download_limit)) ? $download_limit : 'unlimited';
break;
case 'image_id': // Extracts the ID of the main product image
$info = $product->get_image_id();
break;
case 'image': // Extracts the main product image HTML
$info = $product->get_image();
break;
case 'gallery_image_ids': // Extracts the IDs of the product gallery images
$gallery_ids = $product->get_gallery_image_ids();
$info = implode(',', $gallery_ids);
break;
case 'gallery_first_image_id': // Extracts the ID of the first gallery image
$gallery_ids = $product->get_gallery_image_ids();
if (!empty($gallery_ids)) {
$info = $gallery_ids[0];
} else {
$info = null;
}
break;
case 'reviews_allowed': // Extracts if reviews are allowed for the product
$reviews_allowed = $product->get_reviews_allowed();
$info = $reviews_allowed ? 'yes' : 'no';
break;
case 'has_ratings': // Checks if the product has ratings
$rating_count = $product->get_rating_count();
$info = $rating_count > 0 ? 'yes' : 'no';
break;
case 'rating_counts_1': // Extracts the count of reviews with 1-star rating
$info = $product->get_rating_count(1);
break;
case 'rating_counts_2': // Extracts the count of reviews with 2-star rating
$info = $product->get_rating_count(2);
break;
case 'rating_counts_3': // Extracts the count of reviews with 3-star rating
$info = $product->get_rating_count(3);
break;
case 'rating_counts_4': // Extracts the count of reviews with 4-star rating
$info = $product->get_rating_count(4);
break;
case 'rating_counts_5': // Extracts the count of reviews with 5-star rating
$info = $product->get_rating_count(5);
break;
case 'average_rating':
$info = $product->get_average_rating();
$info = number_format($info, 1);
break;
case 'rating_percentage_1': // Calculates the percentage of 1-star ratings
$total_ratings = $product->get_review_count();
$rating_count_1 = $product->get_rating_count(1);
$percentage_1 = $total_ratings > 0 ? round(($rating_count_1 / $total_ratings) * 100) : 0;
$info = $percentage_1;
break;
case 'rating_percentage_2': // Calculates the percentage of 2-star ratings
$total_ratings = $product->get_review_count();
$rating_count_2 = $product->get_rating_count(2);
$percentage_2 = $total_ratings > 0 ? round(($rating_count_2 / $total_ratings) * 100) : 0;
$info = $percentage_2;
break;
case 'rating_percentage_3': // Calculates the percentage of 3-star ratings
$total_ratings = $product->get_review_count();
$rating_count_3 = $product->get_rating_count(3);
$percentage_3 = $total_ratings > 0 ? round(($rating_count_3 / $total_ratings) * 100) : 0;
$info = $percentage_3;
break;
case 'rating_percentage_4': // Calculates the percentage of 4-star ratings
$total_ratings = $product->get_review_count();
$rating_count_4 = $product->get_rating_count(4);
$percentage_4 = $total_ratings > 0 ? round(($rating_count_4 / $total_ratings) * 100) : 0;
$info = $percentage_4;
break;
case 'rating_percentage_5': // Calculates the percentage of 5-star ratings
$total_ratings = $product->get_review_count();
$rating_count_5 = $product->get_rating_count(5);
$percentage_5 = $total_ratings > 0 ? round(($rating_count_5 / $total_ratings) * 100) : 0;
$info = $percentage_5;
break;
case 'review_count': // Extracts the total count of reviews for the product
$info = $product->get_review_count();
break;
case 'find_cart': // Checks if the product is in the cart
$product_id = $product->get_id();
$product_in_cart = false;
$cart = WC()->cart;
if ($cart && !$cart->is_empty()) {
foreach ($cart->get_cart() as $cart_item) {
if ($cart_item['product_id'] == $product_id || $cart_item['variation_id'] == $product_id) {
$product_in_cart = true;
break;
}
}
}
$info = $product_in_cart ? 'yes' : 'no';
break;
case 'featured': // Extracts if the product is featured and converts it to 'yes' or 'no'
$featured = $product->get_featured();
$info = $featured ? 'yes' : 'no';
break;
case 'cart_link': // Extract custom link from cart button
$product_id = $product->get_id();
$cart_link = '?add-to-cart=' . $product_id;
$info = $cart_link;
break;
case 'cart_item_key': // Extracts the cart item key for the product in the cart
$product_id = $product->get_id();
$cart = WC()->cart;
$item_key = '';
if ($cart && !$cart->is_empty()) {
foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
if ($cart_item['product_id'] == $product_id || $cart_item['variation_id'] == $product_id) {
$item_key = $cart_item_key;
break;
}
}
}
$info = !empty($item_key) ? $item_key : 'none';
break;
case 'remove_cart_url': // Extracts the remove URL for the product in the cart
$product_id = $product->get_id();
$cart = WC()->cart;
$remove_url = '';
if ($cart && !$cart->is_empty()) {
foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
if ($cart_item['product_id'] == $product_id || $cart_item['variation_id'] == $product_id) {
$remove_url = wc_get_cart_remove_url($cart_item_key);
break;
}
}
}
$info = !empty($remove_url) ? $remove_url : 'none';
break;
// [Yes it depends on a product]
case strpos($property, 'acf_') === 0:
if (class_exists('acf')) {
$field_name = str_replace('acf_', '', $property);
if (function_exists('get_sub_field')) {
$find_acf_value = get_sub_field($field_name);
$info = !empty($find_acf_value) ? $find_acf_value : 'null';
}
} else {
$info = 'null';
}
break;
default:
$product_id = $product->get_id();
$find_field_value = get_post_meta($product_id, $property, true);
$info = !empty($find_field_value) ? $find_field_value : 'null';
break;
}
return wp_kses_post($info);
}
// Cases that do not depend on a product
switch ($property) {
case 'cart_product_ids': //Extracts all product IDs from the cart
if (!class_exists('WooCommerce')) {
$info = 'none';
break;
}
$cart = WC()->cart;
if (!$cart || $cart->is_empty()) {
$info = 'none';
} else {
$product_ids = [];
foreach ($cart->get_cart() as $cart_item) {
$product_id = !empty($cart_item['variation_id']) ? $cart_item['variation_id'] : $cart_item['product_id'];
if (!in_array($product_id, $product_ids)) {
$product_ids[] = $product_id;
}
}
$info = !empty($product_ids) ? implode(',', $product_ids) : 'none';
}
break;
case 'cart_total_items': //Extracts the total number of items in the cart
$cart = WC()->cart;
$info = $cart ? $cart->get_cart_contents_count() : '0';
break;
case 'cart_total_price': //Extracts the total price of all items in the cart
$cart = WC()->cart;
if ($cart && !$cart->is_empty()) {
$total_price = $cart->get_total('');
$currency_symbol = get_woocommerce_currency_symbol();
$info = $currency_symbol . number_format(floatval($total_price), 2);
} else {
$info = $currency_symbol . '0.00';
}
break;
// [No it depends on a product]
default:
$info = 'Invalid property';
break;
}
return wp_kses_post($info);
}
// woo_css
function woo_css(...$groups) {
$result = '';
foreach ($groups as $group) {
$group_args = explode('|', $group);
$class = trim($group_args[0]);
$woofield = isset($group_args[1]) ? woo_field(trim($group_args[1])) : '';
$unit = isset($group_args[2]) ? trim($group_args[2]) : '';
if (!empty($woofield)) {
$result .= "$class: $woofield$unit; ";
} else {
$result .= "$class; ";
}
}
$result = rtrim($result);
return wp_kses_post($result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment