在开始提问之前,我想让您知道我是一名图形设计师,而不是开发人员。我正在帮助一个 friend 处理他们的网站,所以请原谅我的无知和缺乏知识。
我正在 WordPress 中构建一个包含 WooCommerce 商店的网站。我对 CSS 和 HTML 相当熟悉,但几乎没有 PHP 知识,而且我对 WooCommerce 非常陌生。
我有一个非常具体的目标想要实现,但我真的不知道从哪里开始。
本质上,我想在将特定类别的产品放入购物车后应用条件CSS样式(如果产品被删除则反转)。具体来说,我想更改小部件中图标的颜色并将显示在标题上。因此,效果是,当访问者将“礼物”添加到购物车时,“礼物”图标将“亮起”,提示访问者下一步添加“卡片”等。
我发现以下内容乍一看可能会让我接近,但我不知道如何实现它,所以任何帮助将不胜感激:
// set our flag to be false until we find a product in that category
$cat_check = false;
// check each cart item for our category
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = $cart_item['data'];
// replace 'membership' with your category's slug
if ( has_term( 'membership', 'product_cat', $product->id ) ) {
$cat_check = true;
// break because we only need one "true" to matter here
break;
}
}
// if a product in the cart is in our category, do something
if ( $cat_check ) {
// we have the category, do what we want
}
提前致谢!
最佳答案
在 Hook 函数中尝试以下稍微不同的重新访问代码,这将允许您在购物车元素中找到特定产品类别时添加一些内联 CSS 样式:
add_action( 'wp_head' , 'custom_conditional_css_styles' );
function custom_conditional_css_styles(){
if( WC()->cart->is_empty() ) return; // We exit is cart is empty
// HERE your product category
$product_category = 'membership';
$found = false;
// Loop through cart items checking for our product category
foreach ( WC()->cart->get_cart() as $cart_item ) {
if ( has_term( 'membership', 'product_cat', $cart_item['product_id'] ) ) {
$found = true;
break; // Found we stop the loop
}
}
if ( ! $found ) return; // If the product category is noy found we exit
// Here come your CSS styles
?>
<style>
.my-class { color:red;}
</style>
<?php
}
代码位于事件子主题(或事件主题)的 function.php 文件中。经过测试并有效。
When using
has_term()
with cart items, never use$cart_item['data']->get_id()
but always$cart_item['product_id']
instead.
关于php - 当特定产品类别位于 Woocommerce 购物车中时有条件地应用 CSS 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50704136/