问题:wc_price($price) 未通过过滤器“woocommerce_product_get_regular_price”显示折扣

使用 WooCommerce,我具有以下功能,可让我对产品价格进行折扣:

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

这在任何地方都有效_(在商店、购物车、后端)_,但不在我的自定义产品列表插件中:

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

    //All WP_Query

    echo wc_price($price);
}

这显示没有折扣的正常价格。两段代码都在同一个插件中。

解答

对于信息,wc_price()只是一个用于格式化价格的格式化函数,与$price本身的主要参数无关。您的问题是,在您的第二个函数中,变量$price肯定不使用WC_Product方法get_regular_price(),这在您的情况下是必需的......所以在您的 WP_Query 循环中,您需要获取 WC_Product 对象实例,然后从此对象使用get_regular_price()方法获取价格...

所以试试像_(这是一个例子,因为你没有在你的问题中提供你的WP_Query)_:

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;
}

现在它应该按预期工作。

Logo

WooCommerce社区为您提供最前沿的新闻资讯和知识内容

更多推荐