Wordpress的WooCommerce如何使用回调属性和获取产品的规范



我有一个安装了WooCommerce的WordPress网站。产品规范具有一些全局属性。我想用短代码将它们回调为长描述中的文本。

以下是我能得到的。然而,它只显示了一个属性的标签,我想在它们的属性标签中包含多个属性。

/**
* Attribute shortcode callback.
*/
function testfunction( $atts ) {
global $product;
if( ! is_object( $product ) || ! $product->has_attributes() ){
return;
}
// parse the shortcode attributes
$args = shortcode_atts( array(
'attribute' => ''
), $atts );
// start with a null string because shortcodes need to return not echo a value
$html = '';
if( $args['attribute'] ){
// get the WC-standard attribute taxonomy name
$taxonomy = strpos( $args['attribute'], 'pa_' ) === false ? wc_attribute_taxonomy_name( $args['attribute'] ) : $args['attribute'];
if( taxonomy_is_product_attribute( $taxonomy ) ){
// Get the attribute label.
$attribute_label = wc_attribute_label( $taxonomy );
// Build the html string with the label followed by a clickable list of terms.
// heads up that in WC2.7 $product->id needs to be $product->get_id()
//echo strip_tags( get_the_term_list( $product->id, $taxonomy, $attribute_label . ' ' , ', ', '' ));  


if ($attribute = Test){
echo $product->get_attribute('Test');
}

elseif ($attribute = Test1){
return $product->get_attribute('Test1');
}

}
}
return $html;
}
add_shortcode( 'display_attribute', 'testfunction' );

参考1:Wooccommerce-在前端中显示带有短代码的单个产品属性

我上面提到的[参考文献1]允许我根据需要获取具有多个属性标签的多个属性,但对于这一点,唯一的问题是它还包括我无法拥有的属性名称

简而言之,我想获取"多个属性标签">,但不将属性本身包含在回调文本中。有线索吗?

感谢Kathy@helgatheviking提供了一个真正快速的解决方案。以下是我想要的:希望它能帮助其他社区成员寻找类似的东西。

/**
* Attributes shortcode callback.
*/
function so_39394127_attributes_shortcode( $atts ) {
global $product;
if( ! is_object( $product ) || ! $product->has_attributes() ){
return;
}
// parse the shortcode attributes
$args = shortcode_atts( array(
'attributes' => array_keys( $product->get_attributes() ), // by default show all attributes
), $atts );
// is pass an attributes param, turn into array
if( is_string( $args['attributes'] ) ){
$args['attributes'] = array_map( 'trim', explode( '|' , $args['attributes'] ) );
}
// start with a null string because shortcodes need to return not echo a value
$html = '';
if( ! empty( $args['attributes'] ) ){
foreach ( $args['attributes'] as $attribute ) {
// get the WC-standard attribute taxonomy name
$taxonomy = strpos( $attribute, 'pa_' ) === false ? wc_attribute_taxonomy_name( $attribute ) : $attribute;
if( taxonomy_is_product_attribute( $taxonomy ) ){
// Build the html string with the label followed by a clickable list of terms.
//$html .= get_the_term_list( $product->get_id(), $taxonomy, '<li class="bullet-arrow">': ' , ', ', '</li>' );   
$html .= get_the_term_list( $product->get_id(), $taxonomy, '', ', ', '' );
}
}
// if we have anything to display, wrap it in a <ul> for proper markup
// OR: delete these lines if you only wish to return the <li> elements
if( $html ){
$html = '' . $html . '';
}
}
return $html;
}
add_shortcode( 'display_attributes', 'so_39394127_attributes_shortcode' );

最新更新