显示为WooCommerce产品设置的所有产品属性的短代码



我一直在寻找这样做的方法,但不幸的是我找不到任何东西。

我试图在单个产品的自定义位置显示所有产品的属性和值,由管道分隔(因此,我正在考虑创建一个短代码,因此我可以将其放置在我想要的任何地方)。输出将像这样:

品牌:RENAULT |型号:12 |年份:1973

Woocommerce模板product-attributes.php上的代码在单产品页面上列出了当前产品的属性,但它会在我不想要的地方列出一些样式。

我想用这个代码创建一个短代码,它是:

<?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; ?>

我如何用它创建一个短代码?我知道短代码的一般代码,但我不知道如何实际集成上面的代码:


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'); 

如果这个短代码能像我上面说的那样列出属性和它们的值,那么就太好了(怎么做呢?)

任何帮助都非常感谢。

试试下面的短代码,它将显示为产品及其值设置的所有产品属性,也处理自定义属性:

function get_product_attributes_shortcode($atts ) {
// Extract shortcode attributes
extract( shortcode_atts( array(
'id'    => get_the_ID(),
), $atts, 'display-attributes' ) );
global $product;
if ( ! is_a($product, 'WC_Product') ) {
$product = wc_get_product( $id );
}
if ( is_a($product, 'WC_Product') ) {
$html = []; // Initializing
foreach ( $product->get_attributes() as $attribute => $values ) {
$attribute_name = wc_attribute_label($values->get_name());
$attribute_data = $values->get_data();
$is_taxonomy    = $attribute_data['is_taxonomy'];
$option_values    = array(); // Initializing
// For taxonomy product attribute values
if( $is_taxonomy ) {
$terms = $values->get_terms(); // Get attribute WP_Terms
// Loop through attribute WP_Term(s)
foreach ( $terms as $term ) {
$term_link       = get_term_link( $term, $attribute );
$option_values[] = '<a href="'.$term_link.'">'.$term->name.'</a>';
}
}
// For "custom" product attributes values
else {
// Loop through attribute option values
foreach ( $values->get_options() as $term_name ) {
$option_values[] = $term_name;
}
}
$html[] = '<strong>' . $attribute_name . '</strong>: ' . implode(', ', $option_values);
}
return '<div class="product-attributes">' . implode(' | ', $html) . '<div>';
}
}
add_shortcode( 'display-attributes', 'get_product_attributes_shortcode' );

代码放在活动子主题(或活动主题)的functions.php文件中。

用法:[display-attributes]或具有定义的产品Id[display-attributes id="254"]

您将得到如下显示:BRAND:雷诺|model: 12 |year: 1973

如果您不需要链接的术语,替换为:

$term_link       = get_term_link( $term, $attribute );
$option_values[] = '<a href="'.$term_link.'">'.$term->name.'</a>';

由:

$option_values[] = $term->name;

最新更新