Skip to main content

[Thủ Thuật WordPress] Hướng dẫn ẩn giá trong WooCommerce

Ẩn tất cả giá trong WooCommerce

Hãy bắt đầu với một ví dụ đơn giản. Để ẩn tất cả giá khỏi cửa hàng WooCommerce của bạn, chỉ cần thêm đoạn mã sau vào tệp functions.php của bạn.

add_filter( 'woocommerce_get_price_html', 'QuadLayers_remove_price');
function QuadLayers_remove_price($price){     
     return ;
}

Chỉ hiển thị giá cho quản trị viên

Bây giờ, giả sử bạn muốn ẩn tất cả các mức giá đối với khách truy cập nhưng bạn muốn admin có thể nhìn thấy chúng. Để làm được điều đó, bạn cần thêm điều kiện vào đoạn mã và sử dụng mã sau:

add_filter( 'woocommerce_get_price_html', 'QuadLayers_remove_price');
function QuadLayers_remove_price($price){   
 if ( is_admin() ) return $price; 
     return ;
}

Đoạn mã trên ẩn tất cả giá nhưng hiển thị chúng cho người dùng quản trị. Điều đáng chú ý là đoạn mã sẽ ẩn giá khỏi trang sản phẩm và trang giỏ hàng, vì vậy người mua hàng sẽ có thể nhìn thấy chúng trên trang thanh toán.

Chỉ ẩn giá trong Trang cửa hàng WooCommerce

Để ẩn giá WooCommerce chỉ trên trang cửa hàng, bạn có thể chỉ cần sử dụng tập lệnh sau.

add_filter( 'woocommerce_after_shop_loop_item_title', 'remove_woocommerce_loop_price', 2 ); 
function remove_woocommerce_loop_price() { 
   if( ! is_shop() ) return; // Hide prices only on shop page 
remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 ); 
}

Chỉ ẩn giá trong WooCommerce cho các sản phẩm cụ thể

Giả sử bạn sắp ra mắt một số sản phẩm mới, vì vậy bạn chỉ muốn ẩn giá cho những mặt hàng cụ thể đó. Với đoạn mã sau, bạn có thể ẩn giá của các sản phẩm có ID là 2000 và 1978 và hiển thị giá cho phần còn lại của sản phẩm.

add_filter( 'woocommerce_get_price_html', 'QuadLayers_hide_price_product_ids', 10, 2 );        
    function QuadLayers_hide_price_product_ids( $price, $product ) {
$hide_for_products = array( 2000, 1978 );
if ( in_array( $product->get_id(), $hide_for_products ) ) {
return;
}
else{ 
return $price; // Return price for the all the other products
}
   }

Chỉ ẩn giá trong WooCommerce cho các danh mục cụ thể

Với tập lệnh sau, bạn có thể ẩn giá cho các danh mục cụ thể.

add_filter( 'woocommerce_get_price_html','QuadLayers_hide_price_on_taxonomy');
function QuadLayers_hide_price_on_taxonomy( $price) {
   global $product;
   $hide_for_categories = array( 'posters' );   // Hide for these category slugs / IDs
   if ( has_term( $hide_for_categories, 'product_cat', $product->get_id() ) ) {  // Don't show price when it's in one of the categories
    $price= '';
   }   
   return $price; // Return original price   
   }

Nguồn: Quadlayers