如果用户以前购买过产品,则在WooCommerce购物车页面上的产品名称下方显示消息
如果登录的用户以前已经购买过该产品,我希望在购物车页面上显示通知。
在结账页面上,我设法显示了它 将此checkout/review-order.php添加到第31行if( is_user_logged_in() ) {
$user = wp_get_current_user();
}
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
if ( $_product && $_product->exists() && $cart_item['quantity'] > 0 && apply_filters( 'woocommerce_checkout_cart_item_visible', true, $cart_item, $cart_item_key ) ) {
?>
<tr class="<?php echo esc_attr( apply_filters( 'woocommerce_cart_item_class', 'cart_item', $cart_item, $cart_item_key ) ); ?>">
<td class="product-name">
<?php echo apply_filters( 'woocommerce_cart_item_name', $_product->get_name(), $cart_item, $cart_item_key ) . ' '; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
<?php echo apply_filters( 'woocommerce_checkout_cart_item_quantity', ' <strong class="product-quantity">' . sprintf( '× %s', $cart_item['quantity'] ) . '</strong>', $cart_item, $cart_item_key ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
<?php echo wc_get_formatted_cart_item_data( $cart_item ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
<?php
// Here is your code -- Start
if( is_user_logged_in() && wc_customer_bought_product( $user->user_email, $user->ID, $_product->get_id() ) ) {
echo apply_filters( 'woocommerce_checkout_cart_alredy_bought', '<div class="user-bought">' . sprintf( "Hi %s you already purchased in the past.", $user->first_name ) . '</div>' );
}
// Here is your code -- End
?>
</td>
<td class="product-total">
<?php echo apply_filters( 'woocommerce_cart_item_subtotal', WC()->cart->get_product_subtotal( $_product, $cart_item['quantity'] ), $cart_item, $cart_item_key ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
</td>
</tr>
<?php
}
}
对于cart/cart.php中购物车页面,我需要在第几行添加代码?
解决方案
可以使用woocommerce_after_cart_item_name
操作挂钩
因此您得到:
function action_woocommerce_after_cart_item_name( $cart_item, $cart_item_key ) {
// Only for logged-in users
if ( ! is_user_logged_in() ) return;
// Get current user
$user = wp_get_current_user();
// Get product ID
$product_id = $cart_item['variation_id'] > 0 ? $cart_item['variation_id'] : $cart_item['product_id'];
// If true
if ( wc_customer_bought_product( $user->user_email, $user->ID, $product_id ) ) {
echo '<p class="my-class">' . sprintf( __( 'Hi %s you already purchased this product in the past.', 'woocommerce' ), $user->first_name ) . '</p>';
}
}
add_action( 'woocommerce_after_cart_item_name', 'action_woocommerce_after_cart_item_name', 10, 2 );
相关文章