I keep searching for a way to do this, but I can't find anything unfortunately.
I an trying to display all the product's attributes and values, separated by a pipe, in a custom place on the single-product (so for that I was thinking to create a shortcode, so I can place it anywhere I want). the output would be something like this:
BRAND: RENAULT | MODEL: 12 | YEAR: 1973
The code on the Woocommerce template product-attributes.php lists the attributes of the current product on single-product page, but it will list it with some styles I don't want in a place I don't want.
I want to create a shortcode with that code, which is:
<?php foreach ( $product_attributes as $product_attribute_key => $product_attribute ) : ?>
<?php echo wp_kses_post( $product_attribute['label'] ); ?>: <?php echo wp_kses_post( $product_attribute['value'] ); ?> |
<?php endforeach; ?>
How can I create a shortcode with it? I know the general code for a shortcode, but I don't know how to actually integrate the above one in it:
function custom_attributes_product_page() {
// integrate the required code
// Output needs to be return
return
}
// register shortcode
add_shortcode('custom-attributes', 'custom_attributes_product_page');
Would be great if this shortcode would list the attributes and their values separated by a column, like I said above (how to do that?)
Any help is highly appreciated.
My Answer:
function display_product_attributes_shortcode() {
global $product;
$attributes = $product->get_attributes();
$output = '';
foreach ($attributes as $attribute) {
$output .= $attribute['name'] . ': ' . $attribute['value'] . ' | ';
}
// Remove the last pipe symbol
$output = rtrim($output, ' | ');
return $output;
}
add_shortcode('product_attributes', 'display_product_attributes_shortcode');
You can add this code to your theme's functions.php file or a custom plugin. Then you can use the [product_attributes] shortcode in your single-product template or any other page to display all the product attributes and their values separated by a pipe.
Rate this post
5 of 5 based on 2267 votesComments