Skip to content

Instantly share code, notes, and snippets.

@kartikparmar
Created December 5, 2024 13:48
Show Gist options
  • Save kartikparmar/745b582ecce62546c5c2782ce5e00de7 to your computer and use it in GitHub Desktop.
Save kartikparmar/745b582ecce62546c5c2782ce5e00de7 to your computer and use it in GitHub Desktop.
Display Custom Price and Tax information
<?php
// Add a custom field to the General tab on the product edit page
add_action( 'woocommerce_product_options_general_product_data', 'add_custom_price_option' );
function add_custom_price_option() {
woocommerce_wp_text_input(
array(
'id' => '_custom_price_title',
'label' => __( 'Display Price', 'your-textdomain' ),
'description' => __( 'Enter a custom price title to display on the product page.', 'your-textdomain' ),
'desc_tip' => true,
'type' => 'text',
'placeholder' => __( 'e.g., Special Offer: $99', 'your-textdomain' ),
)
);
woocommerce_wp_text_input(
array(
'id' => '_custom_vat_title',
'label' => __( 'Tax text', 'your-textdomain'),
'description' => __( 'Enter a custom tax text to display on the product page.', 'your-textdomain' ),
'desc_tip' => true,
'type' => 'text',
'placeholder' => __( 'e.g., p.p. excluding VAT (21%)', 'your-textdomain' ),
)
);
}
// Save the custom field value when the product is saved
add_action( 'woocommerce_process_product_meta', 'save_custom_price_option' );
function save_custom_price_option( $post_id ) {
$custom_price_title = isset( $_POST['_custom_price_title'] ) ? sanitize_text_field( $_POST['_custom_price_title'] ) : '';
update_post_meta( $post_id, '_custom_price_title', $custom_price_title );
$custom_price_title = isset( $_POST['_custom_vat_title'] ) ? sanitize_text_field( $_POST['_custom_vat_title'] ) : '';
update_post_meta( $post_id, '_custom_vat_title', $custom_price_title );
}
// Display the custom price title on the product page
add_filter( 'woocommerce_get_price_html', 'display_custom_price_title', 10, 2 );
function display_custom_price_title( $price, $product ) {
if ( is_product() ) {
$custom_price = get_post_meta( $product->get_id(), '_custom_price_title', true );
if ( ! empty( $custom_price ) ) {
$tax_text = get_post_meta( $product->get_id(), '_custom_vat_title', true );
if ( !empty( $tax_text ) ) {
$custom_price .= '&nbsp;<small style="font-size:50%">' . $tax_text . '</small>';
}
return $custom_price;
}
}
return $price;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment