Search code examples
phpwordpresswoocommerceproducthook-woocommerce

wc_price($price) not showing the discount by FILTER "woocommerce_product_get_regular_price"


With WooCommerce, I have the following function that allow me to make a discount on my products prices:

add_filter('woocommerce_product_get_regular_price', 'custom_price' , 99, 2 );
function custom_price( $price, $product )
{
$price = $price - 2;
return $price
}

This is working everywhere (in the shop, in the cart, in the backend), but not in my custom product list plugin:

add_action( 'woocommerce_account_nybeorderlist_endpoint', 'patrickorderlist_my_account_endpoint_content' );
function patrickorderlist_my_account_endpoint_content() {

    //All WP_Query

    echo wc_price($price);
}

This shows the regular price without the discount. Both pieces of code are in the same plugin.


Solution

  • For info, wc_price() is just a formatting function used to format prices and has nothing to do with the $price itself main argument. Your problem is that in your 2nd function, the variable $price certainly doesn't use the WC_Product method get_regular_price(), which is required in your case… So in your WP_Query loop, you need to get the WC_Product object instance, then from this object get the price using the method get_regular_price()

    So try something like (it's an example as you don't provide your WP_Query in your question):

    add_action( 'woocommerce_account_nybeorderlist_endpoint', 'rm_orderlist_my_account_endpoint_content' );
    function rm_orderlist_my_account_endpoint_content() {
    
        $products = new WP_Query( $args ); // $args variable is your arguments array for this query
    
        if ( $products->have_posts() ) :
        while ( $products->have_posts() ) : $products->the_post();
    
        // Get the WC_Product Object instance
        $product = wc_get_product( get_the_id() );
    
        // Get the regular price from the WC_Product Object
        $price   = $product->get_regular_price();
    
        // Output the product formatted price
        echo wc_price($price);
    
        endwhile;
        wp_reset_postdata();
        endif;
    }
    

    Now it should work as expected.