Define your own template tag
One idea is to use the template tag:
<?php the_price();?>
or
<?php the_price( '%.1f' );?>
to change the format to your needs.
Then you can add filters to it as you like.
In your functions.php
file you could add
// setup the price filters:
add_filter( 'the_price' , 'xyz_add_product_price', 1, 1 );
add_filter( 'the_price' , 'xyz_add_commission', 2, 1 );
add_filter( 'the_price' , 'xyz_add_shipping', 3, 1 );
where you use the priority to control the order of the calculations.
The xyz_
is just a prefix that you can change.
The definition of the template tag could look like this:
/**
* Template tag to display the price
* @param string $d Output format
* @return void
*/
function the_price( $d = '' ){
echo get_the_price( $d );
}
where:
/**
* Template tag to return the price
* @param string $d Output format
* @return number $price Price
*/
function get_the_price( $d = '' ){
$price = apply_filters( 'the_price', 0 );
if( empty( $d ) )
$d = '%.2f'; // with 2 decimals
return sprintf( $d, $price );
}
It might be a good idea to check if these template tags already exists with function_exists()
or use an additional custom prefix.
Add the price filters
Your first price filter might be to add the product price:
/**
* Price filter #1
* Add product price
* @param number $price
* @return number $price
*/
function xyz_add_product_price( $price ) {
$product_price = get_post_meta( get_the_ID(), 'product_price', TRUE );
if( ! empty( $product_price ) ){
// convert the values from string to int/float:
$product_price = 1 * $product_price;
// add product price:
return ( $price + $product_price );
}else{
return $price;
}
}
and the second one for the tax commmision:
/**
* Price filter #2
* Add tax commission to the product price
* @param number $price
* @return number $price
*/
function xyz_add_commission( $price = 0 ) {
$tax_commision = get_post_meta( get_the_ID(), 'tax_commision', TRUE );
if( ! empty( $tax_commision ) ){
// convert the values from string to int/float:
$tax_commision = 1 * $tax_commision;
// calculate the commision and add to the price:
return ( $price + ( $tax_commision / 100 ) * $price ) ;
}else{
return $price;
}
}
and finally the third one for the shipping fee:
/**
* Price filter #3
* Add shipping fee to the product price
* @param number $price
* @return number $price
*/
function xyz_add_shipping( $price ) {
$shipping_fee = 10;
return ( $price + $shipping_fee );
}
... and you can add more later on.