WooCommerce技术咨询:如何通过带商品ID的短代码在文章页展示商品属性
Hey there! I’ve been in your shoes before—trying to get WooCommerce product attributes to show up in posts can be tricky when you’re starting out. Let me share a custom shortcode solution that’ll do exactly what you need: display all attributes for a specific product by passing its ID.
First, you’ll need to add this code snippet to your theme’s functions.php file (or a custom plugin—this is safer if you plan to update your theme later):
function display_product_attributes_shortcode($atts) { // Set up default shortcode parameters $atts = shortcode_atts(array( 'id' => '', // Required product ID parameter ), $atts); // Check if a product ID was provided if (empty($atts['id'])) { return '<p>Oops! Please add a valid product ID using the <code>id</code> parameter (e.g., [product_attributes id="99"]).</p>'; } // Fetch the product object from WooCommerce $product = wc_get_product($atts['id']); // Handle cases where the product doesn't exist if (!$product) { return '<p>Sorry, no product found with ID: ' . esc_html($atts['id']) . '</p>'; } // Get all attributes attached to the product $attributes = $product->get_attributes(); // If the product has no attributes if (empty($attributes)) { return '<p>This product doesn’t have any attributes to display.</p>'; } // Build the HTML output for attributes $output = '<div class="post-product-attributes">'; $output .= '<h4>' . esc_html($product->get_name()) . ' - Attributes</h4>'; $output .= '<ul>'; // Loop through each attribute and display its label + values foreach ($attributes as $attribute) { $attribute_label = $attribute->get_name(); $attribute_values = implode(', ', array_map('esc_html', $attribute->get_options())); $output .= '<li><strong>' . esc_html($attribute_label) . ':</strong> ' . $attribute_values . '</li>'; } $output .= '</ul>'; $output .= '</div>'; return $output; } // Register the shortcode with WooCommerce add_shortcode('product_attributes', 'display_product_attributes_shortcode');
How to Use It
Once the code is added, just drop this shortcode into any post or page where you want to show product attributes:
[product_attributes id="99"]
Replace 99 with your target product’s ID, and it’ll render a clean list of all that product’s attributes, including the product name as a heading.
Quick Customization Tips
- Hide the product name: Remove the line
$output .= '<h4>' . esc_html($product->get_name()) . ' - Attributes</h4>';from the code. - Style the output: Target the
.post-product-attributesclass in your theme’s CSS to adjust margins, colors, or layout (e.g., turn the list into a table). - Adjust value formatting: If you want values to display on separate lines instead of comma-separated, replace
implode(', ', ...)withimplode('<br>', ...).
内容的提问来源于stack exchange,提问作者Rémi

