第一个选项是通过 jQuery 和 CSS 隐藏这些字段。您可以在购物车页面上使用各种挂钩,例如 woocommerce_before_calculate_totals 操作挂钩。
注意:因为shop_table 的所有表行都包含相同的类,所以正确的按钮/字段会根据产品 ID 隐藏。
function action_woocommerce_before_calculate_totals( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Only cart
if( ! is_cart() )
return;
// If cart is NOT empty
if ( ! $cart->is_empty() ) {
// Loop
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
// Get an instance of the WC_Product object
$product = $cart_item['data'];
// Get product id
$product_id = $cart_item['product_id'];
// Get name
$original_name = method_exists( $product, 'get_name' ) ? $product->get_name() : $product->post->post_title;
// Compare
if ( $original_name == 'Build Your Own') {
$meta = wc_get_formatted_cart_item_data( $cart_item, true );
$sMeta = substr( $meta, -7 );
$new_name = $original_name . ' - ' . $sMeta;
// Set name
if( method_exists( $product, 'set_name' ) ) {
$product->set_name( $new_name );
} else {
$product->post->post_title = $new_name;
}
} else {
$meta = wc_get_formatted_cart_item_data( $cart_item, true );
// NOT empty
if ( ! empty( $meta ) ) {
// Hide remove button & quantity fields
?>
<script>
jQuery( document ).ready( function($) {
// Selector (product remove)
var product_selector = '[data-product_id="<?php echo $product_id; ?>"]';
// Hide 'remove item'
$( product_selector ).css( 'display', 'none' );
// Hide 'quantity input' (starting from the product remove selector)
$( product_selector ).parent().siblings( '.product-quantity' ).find( '.quantity' ).css( 'display', 'none' );
});
</script>
<?php
}
}
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'action_woocommerce_before_calculate_totals', 10, 1 );
另一个选项是通过woocommerce_cart_item_remove_link 过滤器挂钩隐藏删除按钮。因此,这取决于您的偏好和最终目标,然后您可以对数量字段应用类似的内容。
function filter_woocommerce_cart_item_remove_link( $link, $cart_item_key ) {
// Returns true on the cart page.
if ( is_cart() ) {
// Get cart
$cart = WC()->cart;
// If cart is NOT empty
if ( ! $cart->is_empty() ) {
// Loop
foreach ( $cart->get_cart() as $cart_item ) {
// Get an instance of the WC_Product object
$product = $cart_item['data'];
// Get name
$original_name = method_exists( $product, 'get_name' ) ? $product->get_name() : $product->post->post_title;
// Compare
if ( $original_name == 'Build Your Own') {
$meta = wc_get_formatted_cart_item_data( $cart_item, true );
$sMeta = substr( $meta, -7 );
$new_name = $original_name . ' - ' . $sMeta;
// Set name
if( method_exists( $product, 'set_name' ) ) {
$product->set_name( $new_name );
} else {
$product->post->post_title = $new_name;
}
} else {
$meta = wc_get_formatted_cart_item_data( $cart_item, true );
// NOT empty
if ( ! empty( $meta ) ) {
// Hide remove button
$link = '';
}
}
}
}
}
return $link;
}
add_filter( 'woocommerce_cart_item_remove_link', 'filter_woocommerce_cart_item_remove_link', 10, 2 );