如何在WooCommerce的PHP代码中添加多个产品ID以显示自定义内容?
实现WooCommerce多产品ID显示自定义内容
你只需要把目标产品ID放到一个数组里,用in_array()函数替换原来的单个ID判断逻辑就行,具体修改如下:
修改后的完整代码
add_action( 'woocommerce_single_product_summary', 'add_custom_content_for_specific_product', 15 ); function add_custom_content_for_specific_product() { global $product; // 定义需要显示自定义内容的产品ID数组,用逗号分隔多个ID $target_product_ids = array(37, 42, 56); // 这里可以继续添加更多产品ID // 检查当前产品ID是否在目标数组中,不在则直接返回 if( !in_array( $product->get_id(), $target_product_ids ) ) return; // 自定义内容部分(保持不变) ?> <div class="custom-content product-id-<?php echo $product->get_id(); ?>"> <h3><?php _e("My custom content title", "woocommerce"); ?></h3> <p><?php _e("This is my custom content text, this is my custom content text, this is my custom content text…", "woocommerce"); ?></p> </div> <?php }
关键修改点说明
- 新增
$target_product_ids数组,把需要显示内容的产品ID都放进去,多个ID之间用逗号分隔 - 把原来的
$product->get_id() != 37改成!in_array( $product->get_id(), $target_product_ids ),意思是如果当前产品ID不在目标数组里,就不执行后续内容
如果要添加更多产品ID,直接在数组里继续追加即可,比如写成array(37, 42, 56, 78)。
内容的提问来源于stack exchange,提问作者M K
相关产品推荐
相关产品推荐

