El siguiente snippet (bloque de código que puedes pegar usando un plugin como WPCode), crea un shortcode que permite mostrar como texto los atributos de un producto en la página de producto.
Trae varias comprobaciones de errores, y se usa así:
[vk7k_wc_mostrar_info_atributo_producto name=”talla”]
El shortcode tiene un nombre así de largo porque el que originalmente se llamaba generaba un lote bastante grande de errores.
<?php
// Cambiamos el nombre de la función para que sea único y descriptivo
if ( ! function_exists( 'vk7k_wc_mostrar_info_atributo_producto' ) ) {
/**
* Shortcode para mostrar un atributo específico del producto.
* Uso: [vk7k_wc_product_attribute name="slug_del_atributo"]
* Ejemplo: [vk7k_wc_product_attribute name="horas"] o [vk7k_wc_product_attribute name="pa_horas"]
*/
function vk7k_wc_mostrar_info_atributo_producto( $atts ) {
// Usamos el nuevo tag del shortcode en shortcode_atts para consistencia
$atts = shortcode_atts( array(
'name' => '', // Slug del atributo a mostrar
), $atts, 'vk7k_wc_product_attribute' );
if ( empty( $atts['name'] ) ) {
// Actualizamos el mensaje de error para reflejar el nuevo tag
return "Error en [vk7k_wc_product_attribute]: El atributo 'name' está vacío o no se pasó.";
}
global $product;
if ( ! is_a( $product, 'WC_Product' ) ) {
if ( function_exists('get_the_ID') ) {
$current_post_id = get_the_ID();
if ( $current_post_id && get_post_type( $current_post_id ) === 'product' && function_exists('wc_get_product') ) {
$product_temp = wc_get_product( $current_post_id );
if (is_a($product_temp, 'WC_Product')) {
$product = $product_temp;
}
}
}
}
if ( is_a( $product, 'WC_Product' ) ) {
$attribute_slug_from_shortcode = sanitize_title( $atts['name'] );
$attribute_value = '';
$value_as_is = $product->get_attribute( $attribute_slug_from_shortcode );
$value_with_pa_prefix = '';
if ( strpos( $attribute_slug_from_shortcode, 'pa_' ) !== 0 ) {
$value_with_pa_prefix = $product->get_attribute( 'pa_' . $attribute_slug_from_shortcode );
}
if ( ! empty( $value_as_is ) ) {
$attribute_value = $value_as_is;
} elseif ( ! empty( $value_with_pa_prefix ) ) {
$attribute_value = $value_with_pa_prefix;
}
if ( ! empty( $attribute_value ) ) {
return wp_kses_post( $attribute_value );
} else {
// Actualizamos el mensaje de información
return "[vk7k_wc_product_attribute] Info: Atributo '" . esc_html($atts['name']) . "' no encontrado o sin valor para este producto.";
}
} else {
$debug_post_id = function_exists('get_the_ID') ? get_the_ID() : 'N/A';
$debug_post_type = $debug_post_id !== 'N/A' ? get_post_type($debug_post_id) : 'N/A';
// Actualizamos el mensaje de error
return "Error en [vk7k_wc_product_attribute]: No se pudo determinar el producto. (ID: " . esc_html($debug_post_id) . ", Tipo: " . esc_html($debug_post_type) . ")";
}
}
// Usar el nuevo y único tag del shortcode
add_shortcode( 'vk7k_wc_product_attribute', 'vk7k_wc_mostrar_info_atributo_producto' );
}
?>