How do I display product attributes within the product template feature in WordPress?

I am using WooCommerce and Dokan to build a multi-vendor marketplace. Within the Product template, that displays relevant data to the product, I want it to pull attributes and more importantly attribute values. I've seen this at https://agistit.com.au/ and am looking to get the exact same structure. I'm relatively new to custom things within Wordpress like this so any help will be appreciated. Cheers, I've tried using CoPilot and it got far enough that it was pulling the data but was displaying it very incorrectly. Below is what it got stuck on so hopefully this is the building blocks to the right solution? function display_product_attributes_snippet() { // Start output buffering ob_start(); // Get the products (you can customize the query as needed) $args = array( 'post_type' => 'product', 'posts_per_page' => 10, // Adjust the number of products to display ); $loop = new WP_Query( $args ); // Loop through each product while ( $loop->have_posts() ) : $loop->the_post(); global $product; // Display the product title echo '<h2>' . get_the_title() . '</h2>'; // Check if the product has attributes if ( $product->has_attributes() ) { // Get the product attributes $attributes = $product->get_attributes(); // Loop through each attribute and display it foreach ( $attributes as $attribute ) { // Get attribute label $label = wc_attribute_label( $attribute->get_name() ); // Get attribute value(s) if ( $attribute->is_taxonomy() ) { // For global attributes $terms = wp_get_post_terms( $product->get_id(), $attribute->get_name(), array( 'fields' => 'names' ) ); $value = implode( ', ', $terms ); } else { // For custom attributes $value = implode( ', ', $attribute->get_options() ); } // Display the attribute echo '<p><strong>' . esc_html( $label ) . ':</strong> ' . esc_html( $value ) . '</p>'; } } else { echo '<p>No attributes found for this product.</p>'; } endwhile; // Reset the query wp_reset_postdata(); // Return the buffered content return ob_get_clean(); } // Register the shortcode function register_product_attributes_shortcode() { add_shortcode('product_attributes_snippet', 'display_product_attributes_snippet'); } add_action('init', 'register_product_attributes_shortcode');

Comment (0)

You’ll be in good company