如何在WordPress商品列表中为单个商品隐藏自定义DIV?
问题描述
在WordPress的商品分页、分类列表中,需用PHP代码为ID为1744的特定商品,将标题下方class为EMP-100-TAW-Craciun-Produs-I的自定义DIV设置为display:none;其他商品正常显示该DIV。
现有两段代码:
第一段仅在ID为1744的商品中生成该DIV:
<div class="EMP-100-TAW-Craciun-Produs-I"> <?php if ( get_the_ID() === 1744) { global $product; $regular_price = esc_attr( $product->get_display_price() ); $discount = 10; $currency = esc_attr( get_woocommerce_currency() ); $new_price = $regular_price - ($regular_price * 0.10); echo 'Cumpără acest produs cu doar <span style=" font-size: 20px; color: red; ">'.$new_price.$currency.'</span> prin Cadoul TAW de Crăciun'; } ?> </div>
第二段尝试控制DIV显示,但样式会应用到所有商品列表,无法实现仅针对单个商品的隐藏效果:
<div class="EMP-100-TAW-Craciun-Produs-I"> <?php global $product; $regular_price = esc_attr( $product->get_display_price() ); $discount = 10; $currency = esc_attr( get_woocommerce_currency() ); $new_price = $regular_price - ($regular_price * 0.10); echo 'Cumpără acest produs cu doar <span style=" font-size: 20px; color: red; ">'.$new_price.$currency.'</span> prin Cadoul TAW de Crăciun'; ?> </div> <?php if ( get_the_ID() === 1744) { echo "<style>.EMP-100-TAW-Craciun-Produs-I { display: none; }</style>"; } else{ echo "<style>.EMP-100-TAW-Craciun-Produs-I { display: inherit; }</style>"; } ?>
解决方案
问题核心是第二段代码输出的全局样式会影响所有商品,要实现精准控制,有两种可靠方法:
方法一:动态给目标DIV添加行内样式
直接在DIV标签上根据商品ID判断是否添加隐藏样式,样式仅作用于当前商品的DIV:
<?php global $product; $product_id = get_the_ID(); $is_target = $product_id === 1744; ?> <div class="EMP-100-TAW-Craciun-Produs-I" <?php echo $is_target ? 'style="display:none;"' : ''; ?>> <?php $regular_price = esc_attr( $product->get_display_price() ); $discount = 10; $currency = esc_attr( get_woocommerce_currency() ); $new_price = $regular_price - ($regular_price * 0.10); echo 'Cumpără acest produs cu doar <span style=" font-size: 20px; color: red; ">'.$new_price.$currency.'</span> prin Cadoul TAW de Crăciun'; ?> </div>
方法二:利用商品容器的ID编写精准CSS选择器
WooCommerce商品列表中,每个商品项默认会带有包含商品ID的类(比如post-1744),基于这个类编写样式,仅影响目标商品:
<div class="EMP-100-TAW-Craciun-Produs-I"> <?php global $product; $product_id = get_the_ID(); $regular_price = esc_attr( $product->get_display_price() ); $discount = 10; $currency = esc_attr( get_woocommerce_currency() ); $new_price = $regular_price - ($regular_price * 0.10); echo 'Cumpără acest produs cu doar <span style=" font-size: 20px; color: red; ">'.$new_price.$currency.'</span> prin Cadoul TAW de Crăciun'; ?> </div> <?php if ( $product_id === 1744) { echo "<style>.post-{$product_id} .EMP-100-TAW-Craciun-Produs-I { display: none; }</style>"; } ?>
补充说明
- 方法一无需依赖商品容器的类,兼容性更强,逻辑更直接;
- 方法二保持结构与样式分离,适合需要复用样式逻辑的场景;
- 注意第一段原始代码中缺少
global $product;声明,会导致变量未定义,需补充才能正常运行。
内容的提问来源于stack exchange,提问作者RCI
相关产品推荐
相关产品推荐

