首页 > 解决方案 > 如果从特定存档页面选择产品,则调整 Woocommerce 价格

问题描述

我不确定这是否可能,但感觉应该是这样,所以我将不胜感激。

基本上,我有一个产品列表,我希望通过两个不同的存档(由另一个插件设置)显示这些产品,我可以通过使用简码列出类别来控制显示的产品。不同的档案需要为相同的产品显示不同的价格,有时不列出一个类别中的特定产品。

所以我所做的是设置类别(可以在前端过滤并因此显示它们的名称)具有相同的名称,但每个存档页面的 slug 不同,然后将每个产品添加到具有相同名称的两个类别中以便它们显示在每个档案中。

问题是我需要将一个档案中几乎所有产品的基本价格提高 0.50,但我想不出办法。我可以像这样在视觉上获得正确的结果:

function bbloomer_alter_price_display( $price_html, $product ) {

global $wp_query;
$slug = basename(get_permalink($wp_query->post->ID));

// Only if not null
if ( '' === $product->get_price() ) return $price_html;

  // If on specifc archive page   
  if ( $slug == "eathere" ) {
    $orig_price = wc_get_price_to_display( $product );
    $price_html = wc_price( $orig_price + 0.50 );
  }

return $price_html;
}

add_filter( 'woocommerce_get_price_html', 'bbloomer_alter_price_display', 9999, 2 );

但显然,这只会更新视觉价格,并且一旦将其添加到购物车并结帐,它只会显示基本价格,不会改变。

我知道您应该使用woocommerce_before_calculate_totals 之类的钩子单独更新购物车,但我不知道如何应用它必须来自此存档的逻辑才能修改价格。

此代码适用于他们所在的类别:

add_filter( 'woocommerce_product_get_price', 'custom_sale_price_for_category', 10, 2 );
function custom_sale_price_for_category( $price, $product ) {

  //Get all product categories for the current product
  $terms = wp_get_post_terms( $product->get_id(), 'product_cat' );
  foreach ( $terms as $term ) {
    $categories[] = $term->slug;
  }

  if ( ! empty( $categories ) && in_array( 'eathere-burgers', $categories, true ) ) {
    $price *= ( 1 + 0.50 );
  }

  return $price;
}

但这会影响整个网站的价格,无论他们在哪个存档页面上。如果我补充说它应该只像第一个示例中那样通过 slug 影响存档页面,那么它们会正确显示在存档中,但不会在结帐购物车中更改。

我真的很困惑如何在不复制整个产品列表和调整价格的情况下让它工作。感觉这应该可以通过一些简单的代码实现,但是 Woocommerce 的钩子和过滤器的功能如此密集,我发现很难弄清楚。

有人可以帮忙吗?

标签: phpwordpresswoocommerce

解决方案


我不知道逻辑是否正确,但您可以尝试使用“woocommerce_product_get_price”过滤器中的会话变量来存储存档的值

session_start();
$_SESSION["archive"] = "eathere";

现在在购物车/结帐钩子'woocommerce_before_calculate_totals'上获取相同的会话变量值,不要忘记并 在此钩子中session_start();获取值$_SESSION["archive"]以检查存档 slug 并据此更新价格。


推荐阅读