Skip to content

Instantly share code, notes, and snippets.

@hssktm
Created February 19, 2026 05:21
Show Gist options
  • Select an option

  • Save hssktm/4d4961c3333ee79009fd18c99b88c607 to your computer and use it in GitHub Desktop.

Select an option

Save hssktm/4d4961c3333ee79009fd18c99b88c607 to your computer and use it in GitHub Desktop.
Function to extract data from WooCommerce
The `woo_field($post_id = null, $fields = null, $sizes = ['full'], $exclude = null)` function accepts four arguments.
-The first is the post (product) ID from which the data will be extracted.
-The second corresponds to the fields you want to include; here you can define them one by one according to your needs, which helps avoid loading unnecessary information.
-The third is an array of image sizes. Here you can specify the sizes registered in your WordPress or WooCommerce installation. For example, if you define `woocommerce_thumbnail`, all returned images will use only that size.
-The fourth argument is `exclude`. This is useful when you need to retrieve all available fields but want to exclude specific ones.
/*************************************************************/
#Extract the function from the post product current.
{
product: post {
ID@private
woo_field: php_function_output(
function: "woo_field",
arguments: ["{{ID}}", null ["woocommerce_thumbnail", "woocommerce_single", "woocommerce_gallery_thumbnail"], null ]
)
}
}
#Second way to obtain the content of the current post.
This option is more flexible and allows you to easily
add global data that does not directly depend on the
current post.
{
ID: php_function_output(
function: "get_the_id"
)@private
woo_field: php_function_output(
function: "woo_field",
arguments: ["{{ID}}", null ["woocommerce_thumbnail", "woocommerce_single", "woocommerce_gallery_thumbnail"], null ]
)
}
#One way to retrieve content within a collection.
With this approach, you can use the "include"
argument to request only the necessary fields,
optimizing the query and making it easier
to create product cards.
{
posts_query(
arguments: {
post_type: "product"
post_status: "publish"
posts_per_page: 9
orderby: "title"
order: "ASC"
}
) {
posts {
ID
woo_field: php_function_output(
function: "woo_field"
arguments: [
"{{ID}}",
[
"name",
"price_original",
"is_price_free",
"is_on_sale",
"featured_image",
"stock_status"
],
[
"woocommerce_thumbnail",
"woocommerce_single",
"woocommerce_gallery_thumbnail"
],
null
]
)
}
has_pagination
pagination(
arguments: {
pagination_url_param_name: "posts_page"
}
) {
links
}
posts_count
}
}
function woo_field($post_id = null, $fields = null, $sizes = ['full'], $exclude = null) {
if (!class_exists("WooCommerce")) {
return "";
}
if ($post_id) {
$product = wc_get_product($post_id);
} else {
global $product;
if (!$product) {
$product = wc_get_product(get_the_ID());
}
}
if (!$product) {
return "";
}
// General WooCommerce settings
$date_format = get_option('date_format');
$tax_display_mode = get_option('woocommerce_tax_display_shop') === 'incl';
$currency_symbol = get_woocommerce_currency_symbol();
$currency_pos = get_option('woocommerce_currency_pos');
$decimals = intval(get_option('woocommerce_price_num_decimals'));
$decimal_sep = get_option('woocommerce_price_decimal_sep');
$thousand_sep = get_option('woocommerce_price_thousand_sep');
// Helper function to format prices according to WooCommerce settings
$format_price = function ($price) use ($currency_symbol, $currency_pos, $decimals, $decimal_sep, $thousand_sep) {
if (!is_numeric($price)) return "";
$formatted = number_format(floatval($price), $decimals, $decimal_sep, $thousand_sep);
return match ($currency_pos) {
'left' => $currency_symbol . $formatted,
'right' => $formatted . $currency_symbol,
'left_space' => $currency_symbol . ' ' . $formatted,
'right_space' => $formatted . ' ' . $currency_symbol,
default => $formatted,
};
};
// Helper function to get price with correct tax display mode
$get_active_price = function ($product, $price_value) use ($tax_display_mode) {
return $tax_display_mode ? wc_get_price_including_tax($product, ['price' => $price_value]) : wc_get_price_excluding_tax($product, ['price' => $price_value]);
};
$data = [
// Product ID
"product_id" => $product->get_id(),
// Product type (simple, variable, grouped, etc.)
"type" => $product->get_type(),
// Product name
"name" => $product->get_name(),
// Product slug
"slug" => $product->get_slug(),
// Product SKU or N/A if empty
"sku" => ($sku = $product->get_sku()) !== '' ? $sku : __('N/A', 'woocommerce'),
// Product status (publish, draft, etc.)
"status" => $product->get_status(),
// Is the product featured?
"featured" => $product->get_featured() ? "true" : "false",
// Catalog visibility (visible, hidden, etc.)
"catalog_visibility" => $product->get_catalog_visibility(),
// Full description
"description" => $product->get_description(),
// Short description
"short_description" => $product->get_short_description(),
// Menu order
"menu_order" => $product->get_menu_order(),
// Is it a virtual product?
"virtual" => $product->get_virtual() ? "true" : "false",
// Current date set in settings
"current_site_date" => date_i18n("Y-m-d\TH:i:s"),
// Date created (formatted based on WP settings)
"date_created" => date_i18n($date_format, strtotime($product->get_date_created()->date("Y-m-d"))),
// Date modified (formatted based on WP settings)
"date_modified" => date_i18n($date_format, strtotime($product->get_date_modified()->date("Y-m-d"))),
// Parent ID for variations or grouped items
"parent_id" => $product->get_parent_id(),
// Formatted price string with original/sale pricing (HTML)
"price_original" => (function () use ($product, $format_price, $get_active_price) {
if ($product->is_type('variable')) {
$prices = $product->get_variation_prices();
if (empty($prices['price'])) return "";
$min_price = $get_active_price($product, min($prices['price']));
$max_price = $get_active_price($product, max($prices['price']));
return $format_price($min_price) . ' - ' . $format_price($max_price);
} elseif (is_numeric($product->get_price())) {
$regular_price = $product->get_regular_price();
$sale_price = $product->get_sale_price();
$active_price = $get_active_price($product, $product->get_price());
if ($product->is_on_sale() && $sale_price) {
$reg_fmt = $format_price($get_active_price($product, $regular_price));
$sale_fmt = $format_price($get_active_price($product, $sale_price));
return '<del>' . $reg_fmt . '</del> <ins>' . $sale_fmt . '</ins>';
}
return $format_price($active_price);
}
return "";
})(),
// Current price formatted with currency and tax settings
"price" => (function () use ($product, $format_price, $get_active_price) {
$product_price = $product->get_price();
if (!is_numeric($product_price)) return "";
return $format_price($get_active_price($product, $product_price));
})(),
// Duplicate price field if needed for logic consistency
"price_variable" => (function () use ($product, $format_price, $get_active_price) {
$product_price = $product->get_price();
if (!is_numeric($product_price)) return "";
return $format_price($get_active_price($product, $product_price));
})(),
// Regular price formatted (handles variable products by showing the minimum regular price)
"regular_price" => (function () use ($product, $format_price, $get_active_price) {
$regular_price = null;
if ($product->is_type('variable')) {
$prices = $product->get_variation_prices(false);
if (!empty($prices['regular_price'])) {
$raw = min($prices['regular_price']);
$regular_price = $get_active_price($product, $raw);
}
} else {
$raw = $product->get_regular_price();
if (is_numeric($raw)) {
$regular_price = $get_active_price($product, $raw);
}
}
return is_numeric($regular_price) ? $format_price($regular_price) : "";
})(),
// Price explicitly excluding tax
"price_tax_excluding" => (function () use ($product, $format_price) {
$price = $product->get_price();
if (!is_numeric($price)) return "";
return $format_price(wc_get_price_excluding_tax($product, ['price' => $price]));
})(),
// Check if price is free (empty or 0)
"is_price_free" => ($p = $product->get_price()) === "" || (float)$p === 0.0 ? "true" : "false",
// Checks if a variable or grouped product has different prices among its children
"find_variable_price" => (function () use ($product) {
$prices = [];
if ($product->is_type("variable")) {
foreach ($product->get_available_variations() as $variation) {
$prices[] = $variation["display_price"];
}
} elseif ($product->is_type("grouped")) {
foreach ($product->get_children() as $child_id) {
$child = wc_get_product($child_id);
if ($child) $prices[] = $child->get_price();
}
}
return count(array_unique($prices)) > 1 ? "true" : "false";
})(),
// Price suffix (e.g., inc. VAT)
"tax_suffix" => (function () use ($product) {
$suffix = get_option("woocommerce_price_display_suffix");
if (!$suffix) return "";
$suffix = str_replace("{price_including_tax}", get_woocommerce_currency_symbol() . number_format(wc_get_price_including_tax($product), 2), $suffix);
$suffix = str_replace("{price_excluding_tax}", get_woocommerce_currency_symbol() . number_format(wc_get_price_excluding_tax($product), 2), $suffix);
return $suffix;
})(),
// Tax setting: Is tax included in displayed price?
"tax_included" => get_option("woocommerce_tax_display_shop") === "incl" ? "true" : "false",
// Is the product on sale?
"is_on_sale" => $product->is_on_sale() ? "true" : "false",
// Sale start date
"date_on_sale_from" => (function () use ($product, $date_format) {
$date = $product->get_date_on_sale_from();
return $date ? date_i18n($date_format, strtotime($date)) : "";
})(),
// Sale end date
"date_on_sale_to" => (function () use ($product, $date_format) {
$date = $product->get_date_on_sale_to();
return $date ? date_i18n($date_format, strtotime($date)) : "";
})(),
// Individual sale end components (Year, Month, Day)
"date_on_sale_to_year" => (function () use ($product) {
$date = null;
if ($product->is_type("variable")) {
$children = $product->get_children();
if ($children) {
$child = wc_get_product(reset($children));
$date = $child ? $child->get_date_on_sale_to() : null;
}
} else {
$date = $product->get_date_on_sale_to();
}
return $date ? date_i18n("Y", strtotime($date)) : "";
})(),
"date_on_sale_to_month" => (function () use ($product) {
$date = null;
if ($product->is_type("variable")) {
$children = $product->get_children();
if ($children) {
$child = wc_get_product(reset($children));
$date = $child ? $child->get_date_on_sale_to() : null;
}
} else {
$date = $product->get_date_on_sale_to();
}
return $date ? date_i18n("m", strtotime($date)) : "";
})(),
"date_on_sale_to_day" => (function () use ($product) {
$date = null;
if ($product->is_type("variable")) {
$children = $product->get_children();
if ($children) {
$child = wc_get_product(reset($children));
$date = $child ? $child->get_date_on_sale_to() : null;
}
} else {
$date = $product->get_date_on_sale_to();
}
return $date ? date_i18n("d", strtotime($date)) : "";
})(),
// Discount percentage
"discount_percentage" => (function () use ($product) {
$regular = $product->get_regular_price();
$sale = $product->get_sale_price();
if (is_numeric($regular) && is_numeric($sale) && $regular > 0) {
return abs(round((($regular - $sale) / $regular) * 100));
}
return "";
})(),
// Discount amount formatted
"discount_amount" => (function () use ($product) {
$regular = $product->get_regular_price();
$sale = $product->get_sale_price();
if (!is_numeric($regular) || !is_numeric($sale) || $regular <= 0) return "";
$tax_mode = get_option("woocommerce_tax_display_shop");
if ($tax_mode === "incl") {
$discount = wc_get_price_including_tax($product, ["price" => $regular]) - wc_get_price_including_tax($product, ["price" => $sale]);
} else {
$discount = wc_get_price_excluding_tax($product, ["price" => $regular]) - wc_get_price_excluding_tax($product, ["price" => $sale]);
}
$formatted = number_format($discount, get_option("woocommerce_price_num_decimals"), get_option("woocommerce_price_decimal_sep"), get_option("woocommerce_price_thousand_sep"));
$symbol = get_woocommerce_currency_symbol();
$pos = get_option("woocommerce_currency_pos");
return match ($pos) {
"left" => $symbol . $formatted,
"right" => $formatted . $symbol,
"left_space" => $symbol . " " . $formatted,
"right_space" => $formatted . " " . $symbol,
default => $formatted,
};
})(),
// Data for swatches and variation attributes
"attributes_data" => (function () use ($product, $sizes) {
if (!$product->is_type("variable")) return [];
$attributes = $product->get_attributes();
$data = [];
$placeholder_id = get_option("woocommerce_placeholder_image", 0);
foreach ($attributes as $attribute) {
if (!$attribute->get_variation()) continue;
$taxonomy = $attribute->get_name();
$attr_key = sanitize_title($taxonomy);
$attr_name = str_replace("pa_", "", $taxonomy);
$attr_id = wc_attribute_taxonomy_id_by_name($attr_name);
$swatch_type = (get_post_meta($product->get_id(), "_rc_sw_type_" . $attr_key, true) ?: get_option("rc_wc_swatch_type_" . $attr_id)) ?: "select";
$values = [];
foreach ($attribute->get_options() as $option) {
if ($attribute->is_taxonomy()) {
$term = get_term($option, $taxonomy);
if (!$term) continue;
$value = $term->slug;
$label = $term->name;
$term_id = $term->term_id;
} else {
$value = $option;
$label = $option;
$term_id = 0;
}
$c1 = get_post_meta($product->get_id(), "_rc_sw_c1_" . $attr_key . "_" . sanitize_title($value), true);
if ($c1 === "" && $term_id) $c1 = get_term_meta($term_id, "rc_swatch_color_1", true);
$c2 = get_post_meta($product->get_id(), "_rc_sw_c2_" . $attr_key . "_" . sanitize_title($value), true);
if ($c2 === "" && $term_id) $c2 = get_term_meta($term_id, "rc_swatch_color_2", true);
$img = get_post_meta($product->get_id(), "_rc_sw_img_" . $attr_key . "_" . sanitize_title($value), true);
if (!$img && $term_id) $img = get_term_meta($term_id, "rc_swatch_image_id", true);
if (!$img && $swatch_type === "image") {
$variations = $product->get_available_variations();
foreach ($variations as $variation) {
$attr_lookup = "attribute_" . $taxonomy;
if (isset($variation["attributes"][$attr_lookup]) && $variation["attributes"][$attr_lookup] === $value) {
$img = $variation["image_id"];
break;
}
}
}
$final_img_id = $img ?: $placeholder_id;
$image_urls = array_reduce($sizes, function ($carry, $size) use ($final_img_id) {
$url = wp_get_attachment_image_url($final_img_id, $size);
$carry[$size] = $url ?: wc_placeholder_img_src($size);
return $carry;
}, []);
$values[] = [
"value" => $value,
"label" => $label,
"attribute_color_1" => $c1 ?: "",
"attribute_color_2" => $c2 ?: "",
"attribute_image_id" => $final_img_id ?: "",
"attribute_images" => $image_urls,
"attribute_overridden" => (get_post_meta($product->get_id(), "_rc_sw_c1_" . $attr_key . "_" . sanitize_title($value), true) !== "" || get_post_meta($product->get_id(), "_rc_sw_c2_" . $attr_key . "_" . sanitize_title($value), true) !== "" || get_post_meta($product->get_id(), "_rc_sw_img_" . $attr_key . "_" . sanitize_title($value), true))
];
}
$data[] = [
"name" => wc_attribute_label($taxonomy),
"id" => $attr_key,
"attribute" => "attribute_" . $attr_key,
"swatch_type" => $swatch_type,
"values" => $values
];
}
return $data;
})(),
// Additional attributes for product info tab
"additional_attributes_data" => array_values(array_filter(array_map(function($attribute) use ($product) {
if (!$attribute->get_visible()) return null;
$name = wc_attribute_label($attribute->get_name());
$values = [];
if ($attribute->is_taxonomy()) {
foreach ($attribute->get_terms() as $term) {
$values[] = ["value_name" => $term->name];
}
} else {
foreach ($attribute->get_options() as $option) {
$values[] = ["value_name" => trim($option)];
}
}
return [
"attribute_name" => $name,
"attribute_values" => $values,
"value_string" => implode(", ", array_column($values, "value_name"))
];
}, $product->get_attributes()))),
// Data for grouped products (Recursive call to get all filtered fields for each child)
"grouped_products_data" => $product->is_type("grouped") ? array_values(array_filter(array_map(function($child_id) use ($sizes) {
return woo_field($child_id, null, $sizes);
}, $product->get_children()))) : "",
// Variations JSON for variable products
"variations_json" => $product->is_type("variable") ? $product->get_available_variations() : "",
// IDs of children products
"children" => ($ids = implode(", ", $product->get_children())) !== "" ? $ids : "none",
// Featured image URLs
"featured_image" => ($image_id = $product->get_image_id() ?: get_option("woocommerce_placeholder_image", 0)) ? array_reduce($sizes, function ($carry, $size) use ($image_id) {
if ($url = wp_get_attachment_image_url($image_id, $size)) {
$carry[$size] = $url;
}
return $carry;
}, []) : "",
// Gallery image URLs
"gallery" => array_values(array_map(function ($id) use ($sizes) {
$item = [];
foreach ($sizes as $size) {
$item[$size] = wp_get_attachment_image_url($id, $size);
}
return $item;
}, (array) $product->get_gallery_image_ids())),
// First image from the gallery
"gallery_first_image" => (function () use ($product, $sizes) {
$ids = $product->get_gallery_image_ids();
if (empty($ids)) return "";
$image_id = $ids[0];
return array_reduce($sizes, function ($carry, $size) use ($image_id) {
if ($url = wp_get_attachment_image_url($image_id, $size)) {
$carry[$size] = $url;
}
return $carry;
}, []);
})(),
// Stock management and quantity
"manage_stock" => $product->get_manage_stock() ? "true" : "false",
// Actual stock quantity
"stock_quantity" => (function () use ($product) {
if ($product->is_type("variable")) {
$total = 0;
foreach ($product->get_children() as $variation_id) {
$variation = wc_get_product($variation_id);
$qty = $variation ? $variation->get_stock_quantity() : null;
if ($qty !== null) $total += $qty;
}
return $total;
}
return $product->get_stock_quantity();
})(),
// Stock status (instock, outofstock) and display text
"stock_status" => $product->get_stock_status(),
"stock_text" => (function () use ($product) {
if ($product->managing_stock()) {
return wp_strip_all_tags(wc_get_stock_html($product));
}
return $product->is_in_stock() ? __("In stock", "woocommerce") : __("Out of stock", "woocommerce");
})(),
// Backorders setting
"is_backorders_notify" => ($product->get_backorders() === 'notify') ? "true" : "false",
// Sales and tax details
"total_sales" => $product->get_total_sales(),
"tax_status" => $product->get_tax_status(),
"tax_class" => $product->get_tax_class(),
// Miscellaneous product settings
"sold_individually" => $product->get_sold_individually() ? "true" : "false",
"purchase_note" => $product->get_purchase_note(),
"shipping_class_id" => $product->get_shipping_class_id(),
// Dimensions and weight
"weight" => $product->get_weight() . " " . get_option("woocommerce_weight_unit"),
"length" => $product->get_length() . " " . get_option("woocommerce_dimension_unit"),
"width" => $product->get_width() . " " . get_option("woocommerce_dimension_unit"),
"height" => $product->get_height() . " " . get_option("woocommerce_dimension_unit"),
"dimensions" => wc_format_dimensions($product->get_dimensions(false)),
// Upsell and Cross-sell IDs
"upsell_ids" => ($ids = implode(",", $product->get_upsell_ids())) !== "" ? $ids : "none",
"cross_sell_ids" => ($ids = implode(",", $product->get_cross_sell_ids())) !== "" ? $ids : "none",
// Term IDs (categories and tags)
"category_ids" => implode(",", $product->get_category_ids()),
"tag_ids" => implode(",", $product->get_tag_ids()),
// Downloadable product settings
"downloads" => wp_json_encode($product->get_downloads()),
"download_expiry" => $product->get_download_expiry(),
"downloadable" => $product->get_downloadable() ? "true" : "false",
"download_limit" => ($limit = $product->get_download_limit()) !== -1 && !empty($limit) ? $limit : "unlimited",
// Reviews and ratings
"reviews_allowed" => (get_option('woocommerce_enable_reviews') === 'yes' && $product->get_reviews_allowed()) ? "true" : "false",
"has_ratings" => $product->get_rating_count() > 0 ? "true" : "false",
"rating_counts_1" => $product->get_rating_count(1),
"rating_counts_2" => $product->get_rating_count(2),
"rating_counts_3" => $product->get_rating_count(3),
"rating_counts_4" => $product->get_rating_count(4),
"rating_counts_5" => $product->get_rating_count(5),
"average_rating" => number_format($product->get_average_rating(), 1),
"rating_percentage_1" => ($total = $product->get_review_count()) > 0 ? round(($product->get_rating_count(1) / $total) * 100) : 0,
"rating_percentage_2" => ($total = $product->get_review_count()) > 0 ? round(($product->get_rating_count(2) / $total) * 100) : 0,
"rating_percentage_3" => ($total = $product->get_review_count()) > 0 ? round(($product->get_rating_count(3) / $total) * 100) : 0,
"rating_percentage_4" => ($total = $product->get_review_count()) > 0 ? round(($product->get_rating_count(4) / $total) * 100) : 0,
"rating_percentage_5" => ($total = $product->get_review_count()) > 0 ? round(($product->get_rating_count(5) / $total) * 100) : 0,
"review_count" => $product->get_review_count(),
// Check if product is in the current cart
"find_cart" => (function () use ($product) {
$cart = WC()->cart;
if (!$cart || $cart->is_empty()) return "false";
$product_id = $product->get_id();
foreach ($cart->get_cart() as $item) {
if ($item["product_id"] == $product_id || $item["variation_id"] == $product_id) {
return "true";
}
}
return "false";
})(),
// External product settings
"button_external_url" => $product->is_type('external') ? $product->get_product_url() : '',
"button_external_text" => $product->is_type('external') ? ($product->get_button_text() ? $product->get_button_text() : $product->add_to_cart_text()) : $product->add_to_cart_text(),
// CSS class for AJAX add to cart
"ajax_add_to_cart_class" => get_option("woocommerce_enable_ajax_add_to_cart") === "yes" ? "ajax_add_to_cart" : "",
// Detection for Builderius template
"is_builderius_template" => (isset($_GET["builderius_template"]) || (isset($_SERVER["HTTP_REFERER"]) && strpos($_SERVER["HTTP_REFERER"], "builderius_template") !== false)) ? "true" : "false",
// Purchase quantities
"min_purchase_quantity" => $product->get_min_purchase_quantity(),
"max_purchase_quantity" => ($max = $product->get_max_purchase_quantity()) > 0 ? $max : "",
// Unique ID for accessibility
"id_accessibility" => 'rc_' . uniqid(),
// Add to cart action URL
"cart_action_url" => esc_url($product->get_permalink()),
// Sample messages for template builders
"messages" => (function() {
$is_builderius = (isset($_GET["builderius_template"]) || (isset($_SERVER["HTTP_REFERER"]) && strpos($_SERVER["HTTP_REFERER"], "builderius_template") !== false));
if (!$is_builderius) {
return [];
}
return [
["type" => "success", "highlight" => "Success:", "content" => "Your cart has been updated.", "button_url" => "", "button_text" => ""],
["type" => "success", "highlight" => "“Product Name”", "content" => "has been added to your cart.", "button_url" => "/cart/", "button_text" => "View cart"],
["type" => "error", "highlight" => "Error:", "content" => "Billing Postcode is a required field.", "button_url" => "#billing_postcode", "button_text" => "Fix"],
["type" => "error", "highlight" => "Coupon “SAVE20”", "content" => "does not exist!", "button_url" => "", "button_text" => ""],
["type" => "info", "highlight" => "Note:", "content" => "Have a discount code? Click here to enter your code", "button_url" => "#", "button_text" => "Enter code"],
["type" => "info", "highlight" => "Shipping", "content" => "options will be updated during checkout.", "button_url" => "", "button_text" => ""]
];
})(),
];
if (is_array($fields)) {
$data = array_intersect_key($data, array_flip($fields));
if (is_array($exclude)) {
$data = array_diff_key($data, array_flip($exclude));
}
if (count($fields) === 1) {
$key = $fields[0];
return isset($data[$key]) ? $data[$key] : "";
}
}
return $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment