我在结账页面中为产品添加了删除按钮。
代码-
function add_delete( $product_title, $cart_item, $cart_item_key ) {
if ( is_checkout() ) {
/* Get Cart of the user */
$cart = WC()->cart->get_cart();
foreach ( $cart as $cart_key => $cart_value ){
if ( $cart_key == $cart_item_key ){
$product_id = $cart_item[\'product_id\'];
$_product = $cart_item[\'data\'] ;
/*Add delete icon */
$return_value = sprintf(
\'<a href="%s" class="remove" title="%s" data-product_id="%s" data-product_sku="%s" data-cart_item_key="%s">×</a>\',
esc_url( WC()->cart->get_remove_url( $cart_key ) ),
__( \'Remove this item\', \'woocommerce\' ),
esc_attr( $product_id ),
esc_attr( $_product->get_sku() ),
esc_attr( $cart_item_key )
);
/* Add product name */
$return_value .= \' <span class = "product_name" >\' . $product_title . \'</span>\' ;
return $return_value;
}
}
}else{
$_product = $cart_item[\'data\'] ;
$product_permalink = $_product->is_visible() ? $_product->get_permalink( $cart_item ) : \'\';
if ( ! $product_permalink ) {
$return_value = $_product->get_title() . \' \';
} else {
$return_value = sprintf( \'<a href="%s">%s</a>\', esc_url( $product_permalink ), $_product->get_title());
}
return $return_value;
}
}
add_filter (\'woocommerce_cart_item_name\', \'add_delete\' , 10, 3 );
它工作得很好。但它刷新整个页面以删除产品,这与购物车页面不同。
Cart页面使用ajax删除产品。我也在尝试做同样的事情。但是,问题是我对Ajax知之甚少。
这是我试过的。
JavaScript
jQuery(document).ready(function($){
$(document).on(\'click\', \'tr.cart_item a.remove\', function (e)
{
e.preventDefault();
var product_id = $(this).attr("data-product_id"),
cart_item_key = $(this).attr("data-cart_item_key"),
product_container = $(this).parents(\'.shop_table\');
// Add loader
product_container.block({
message: null,
overlayCSS: {
cursor: \'none\'
}
});
$.ajax({
type: \'POST\',
dataType: \'json\',
url: wc_checkout_params.ajax_url,
data: {
action: "product_remove",
product_id: product_id,
cart_item_key: cart_item_key
},
success: function(response) {
if ( ! response || response.error )
return;
var fragments = response.fragments;
// Replace fragments
if ( fragments ) {
$.each( fragments, function( key, value ) {
$( key ).replaceWith( value );
});
}
}
});
});
});
还有PHP
function warp_ajax_product_remove()
{
// Get order review fragment
ob_start();
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item)
{
if($cart_item[\'product_id\'] == $_POST[\'product_id\'] && $cart_item_key == $_POST[\'cart_item_key\'] )
{
WC()->cart->remove_cart_item($cart_item_key);
}
}
WC()->cart->calculate_totals();
WC()->cart->maybe_set_cart_cookies();
woocommerce_order_review();
$woocommerce_order_review = ob_get_clean();
}
add_action( \'wp_ajax_product_remove\', \'warp_ajax_product_remove\' );
add_action( \'wp_ajax_nopriv_product_remove\', \'warp_ajax_product_remove\' );
它会删除产品,但不会更新签出页面。
你们能帮帮我吗?非常感谢。