我在Wordpress中使用WooCommerce并尝试在商店展示(存档产品)中为每个产品添加额外信息。
我正在尝试添加一个添加到购物车按钮,以及一些额外的属性。
我可以轻松添加购物车按钮:
add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 20 );
我可以使用我用此
保存的函数添加该属性add_action('woocommerce_after_shop_loop_item_title', 'isa_woo_get_one_pa', 21);
每项工作都是自己的,但如果我尝试两者都会导致产品展示出现混乱。
以下是成功插入的购物车按钮: Cart button only
以下是购物车和属性: Cart and attribute together
我在functions.php中的总代码如下:
/**
* WooCommerce: Show only one custom product attribute above Add-to-cart button on single product page.
*/
function isa_woo_get_one_pa(){
// Edit below with the title of the attribute you wish to display
$desired_att = 'Gauge';
global $product;
$attributes = $product->get_attributes();
if ( ! $attributes ) {
return;
}
$out = '';
foreach ( $attributes as $attribute ) {
if ( $attribute['is_taxonomy'] ) {
// sanitize the desired attribute into a taxonomy slug
$tax_slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '_', $desired_att)));
// if this is desired att, get value and label
if ( $attribute['name'] == 'pa_' . $tax_slug ) {
$terms = wp_get_post_terms( $product->get_id(), $attribute['name'], 'all' );
// get the taxonomy
$tax = $terms[0]->taxonomy;
// get the tax object
$tax_object = get_taxonomy( $tax );
// get tax label
if ( isset ( $tax_object->labels->singular_name ) ) {
$tax_label = $tax_object->labels->singular_name;
} elseif ( isset( $tax_object->label ) ) {
$tax_label = $tax_object->label;
// Trim label prefix since WC 3.0
if ( 0 === strpos( $tax_label, 'Product ' ) ) {
$tax_label = substr( $tax_label, 8 );
}
}
foreach ( $terms as $term ) {
$out .= '<span class="attribute-label">' . $tax_label . ': </span> ';
$out .= '<span class="attribute-value">' . $term->name . '</span></li>';
}
} // our desired att
} else {
// for atts which are NOT registered as taxonomies
// if this is desired att, get value and label
if ( $attribute['name'] == $desired_att ) {
$out .= $attribute['name'] . ': ';
$out .= $attribute['value'];
}
}
}
echo $out;
}
//add_action('woocommerce_after_shop_loop_item_title', 'isa_woo_get_one_pa', 21);
add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 20 );