Community
Administrator
Staff member
To expose WooCommerce product variations as dynamic tags in Elementor, follow these steps to create a custom dynamic tag that displays variation attributes:
Step 1: Create a Custom Dynamic Tag Class
Add the following code to your theme's functions.php or a custom plugin: Code:
<?php
use Elementor\Core\DynamicTags\Tag;
use Elementor\Modules\DynamicTags\Module;
class Elementor_Product_Variation_Attribute_Tag extends Tag {
public function get_name() {
return 'wc-product-variation-attribute';
}
public function get_title() {
return __('Product Variation Attribute', 'your-textdomain');
}
public function get_group() {
return 'woocommerce';
}
public function get_categories() {
return [ Module::TEXT_CATEGORY ];
}
protected function _register_controls() {
$this->add_control(
'attribute_slug',
[
'label' => __('Attribute Slug', 'your-textdomain'),
'type' => \Elementor\Controls_Manager::TEXT,
'placeholder' => 'e.g., pa_color',
]
);
}
public function get_value(array $options = []) {
$settings = $this->get_settings();
$attribute_slug = $settings['attribute_slug'];
if (empty($attribute_slug)) return '';
global $product;
if (!$product || !$product->is_type('variable')) return '';
$variations = $product->get_available_variations();
$values = [];
foreach ($variations as $variation_data) {
$variation = wc_get_product($variation_data['variation_id']);
$attributes = $variation->get_attributes();
if (isset($attributes[$attribute_slug])) {
$value = $attributes[$attribute_slug];
// Handle taxonomy attributes
if (taxonomy_exists($attribute_slug)) {
$term = get_term_by('slug', $value, $attribute_slug);
if ($term) $value = $term->name;
}
$values[] = $value;
}
}
$values = array_unique($values);
return implode(', ', $values);
}
}
// Register the dynamic tag
add_action('elementor/dynamic_tags/register', function ($dynamic_tags) {
require_once('path/to/your/class-file.php'); // Adjust if necessary
$dynamic_tags->register(new Elementor_Product_Variation_Attribute_Tag());
}); Step 2: Using the Dynamic Tag in Elementor
- Edit your template/page with Elementor.
- Add a text widget where you want to display the variations.
- Enable dynamic content by clicking the dynamic tag icon in the text widget.
- Select "Product Variation Attribute" from the WooCommerce group.
- Enter the attribute slug (e.g., pa_color for color variations).
- Save and preview to see the dynamic list of variation attributes.
Key Features:
- Attribute Slug Input: Users specify which product attribute to display (e.g., pa_size, pa_color).
- Taxonomy Handling: Automatically converts term slugs to readable names.
- Unique Values: Ensures each attribute value is listed only once.
Notes:
- Global Product Check: Only works on variable product pages.
- Performance: Efficiently fetches and processes variation data.
- Custom Attributes: Supports both taxonomy-based and custom product attributes.
