How can I render HTML code in the Product Attributes Description in WordPress WooCommerce? Despite trying a custom plugin code, the HTML always displays as plain text in the Attribute Description field.
Custom Plugin code which i tested but not working.
The HTML always renders as plane text in the Attribute Description.
<?php
/*
Plugin Name: Custom Product Attribute Description
Description: Allows adding HTML descriptions to WooCommerce product attributes.
Version: 1.0
Author: Your Name
*/
// Adding the custom field to product attributes
add_action('woocommerce_product_after_variable_attributes', 'add_custom_attribute_description_field', 10, 3);
function add_custom_attribute_description_field($product, $loop, $variations) {
$html_value = get_post_meta($product->get_id(), 'attribute_description', true);
echo '<div class="form-row form-row-wide">';
echo '<p class="form-field">';
echo '<label for="attribute_description[' . $loop . ']">' . __('Attribute Description', 'woocommerce') . '</label>';
echo '<textarea id="attribute_description[' . $loop . ']" name="attribute_description[' . $loop . ']" rows="5" cols="40" class="input-text">' . esc_textarea($html_value) . '</textarea>';
echo '</p>';
echo '</div>';
}
// Saving the custom field value
add_action('woocommerce_save_product_variation', 'save_custom_attribute_description_field', 10, 2);
function save_custom_attribute_description_field($post_id, $i) {
if (isset($_POST['attribute_description'][$i])) {
$allowed_html = array(
'a' => array(
'href' => array(),
'title' => array(),
),
'br' => array(),
'strong' => array(),
// Add more allowed tags as needed
);
$html_value = wp_kses($_POST['attribute_description'][$i], $allowed_html);
update_post_meta($post_id, 'attribute_description', $html_value);
}
}
// Displaying the custom attribute description
add_filter('woocommerce_display_product_attributes', 'display_html_in_product_attributes', 10, 2);
function display_html_in_product_attributes($product_attributes, $product) {
$html_value = get_post_meta($product->get_id(), 'attribute_description', true);
if (!empty($html_value)) {
$product_attributes['Custom Description'] = array(
'label' => __('Description', 'woocommerce'),
'value' => wp_kses_post($html_value) // Output sanitized HTML
);
}
return $product_attributes;
}
Adding HTML to Attribute description.
Testing HTML description
New contributor
Yalenka is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.