Thiết kế web

Chuyển giá sản phẩm 0đ hoặc hết hàng thành liên hệ trong WordPress

Khi bạn sử dụng Woocommerce để xây dựng website bán hàng sẽ có những lúc sản phẩm bạn để trống phần giá hoặc nhập 0 để người dùng liên hệ và báo giá sau. Lúc này bạn sẽ cần phải thay giá 0đ bằng nút liên hệ hoặc số điện thoại của bạn. Trong WordPress bạn thực hiện như sau:

Bạn vào theme đang active và tìm đến file functions.php sau đó nhập đoạn code sau:

function webbanhang_wc_custom_format_price( $price, $product ) {
    if ( $product->get_price() == 0 ) {
        if ( $product->is_on_sale() && $product->get_regular_price() ) {
            $regular_price = wc_get_price_to_display( $product, array( 'qty' => 1, 'price' => $product->get_regular_price() ) );
 
            $price = wc_format_price_range( $regular_price, __( 'Free!', 'woocommerce' ) );
        } else {
            $price = '<span class="amount">' . __( 'Liên hệ', 'woocommerce' ) . '</span>';
        }
    }
    return $price;
}
add_filter( 'woocommerce_get_price_html', 'webbanhang_wc_custom_format_price', 10, 2 );

Chuyển giá sản phẩm hết hàng thành “Liên hệ”

Để hiện “Liên hệ” khi 1 sản phẩm hết hàng bạn chỉ cần thêm đoạn code sau vào functions.php của theme đang active

function webbanhang_show_contact_out_of_stock( $price, $product ) {
    if ( !is_admin() && !$product->is_in_stock()) {
       $price = '<span class="amount">' . __( 'Liên hệ', 'woocommerce' ) . '</span>';
    }
    return $price;
}
add_filter( 'woocommerce_get_price_html', 'webbanhang_show_contact_out_of_stock', 99, 2 );