WooCommerce教程:将钩子触发的自定义拍卖字段函数转换为短代码以解决Divi Builder位置异常问题
将WooCommerce拍卖信息字段转换为短代码适配Divi Builder
没问题,我帮你把原来的拍卖信息字段转换成可在Divi Builder中自由放置的短代码,完美解决位置异常的问题。下面是完整的实现方案:
替换原有代码
把你之前在functions.php里的add_action代码替换成以下短代码注册函数:
// 注册拍卖信息短代码 add_shortcode( 'auction_details', 'render_auction_information_shortcode' ); function render_auction_information_shortcode() { // 确保在单个产品页面生效,获取当前产品对象 global $product; // 非产品页面或非拍卖产品时返回空,避免错误 if ( ! is_product() || ! $product || ! method_exists( $product, 'get_auction_status' ) ) { return ''; } // 开启输出缓冲,捕获HTML内容 ob_start(); ?> <div class="et_pb_row property_page_row"> <div class="property-content"> <h2>Auction Details</h2> <div class="property-overview"> <ul> <li> Auction Status <strong><?php $type = $product->get_auction_status(); switch ( $type ) { case 'non-started': echo esc_attr__( 'Not Started', 'yith-auctions-for-woocommerce' ); break; case 'started': echo esc_attr__( 'Started', 'yith-auctions-for-woocommerce' ); break; case 'finished': echo esc_attr__( 'Finished', 'yith-auctions-for-woocommerce' ); break; } ?></strong> </li> <li> Auction Type <strong><?php echo esc_html( $product->get_auction_type() ); ?></strong> </li> <li> Auction Start Date <strong><?php $dateinic = $product->get_start_date(); if ( $dateinic ) { $format_date = get_option( 'yith_wcact_general_date_format', 'j/n/Y' ); $format_time = get_option( 'yith_wcact_general_time_format', 'h:i:s' ); $format = $format_date . ' ' . $format_time; $date = get_date_from_gmt( date( 'Y-m-d H:i:s', $dateinic ), $format ); echo esc_html( $date ); } ?></strong> </li> <li> Auction End Date <strong><?php $dateclose = $product->get_end_date(); if ( $dateclose ) { $format_date = get_option( 'yith_wcact_general_date_format', 'j/n/Y' ); $format_time = get_option( 'yith_wcact_general_time_format', 'h:i:s' ); $format = $format_date . ' ' . $format_time; $date = get_date_from_gmt( date( 'Y-m-d H:i:s', $dateclose ), $format ); echo esc_html( $date ); } ?></strong> </li> </ul> </div> </div> </div> <?php // 返回捕获的HTML内容 return ob_get_clean(); }
关键优化说明
- 短代码注册:用
add_shortcode创建了名为auction_details的短代码,你可以直接在Divi模块中调用 - 安全校验:增加了产品对象和拍卖方法的判断,避免在非产品页面出现错误
- 输出控制:用
ob_start()和ob_get_clean()捕获HTML内容,符合短代码返回内容的要求(不能直接echo输出) - 安全输出:给动态内容添加了
esc_html()/esc_attr(),提升代码安全性
在Divi Builder中使用
- 打开需要编辑的产品页面,启用Divi Builder
- 添加一个Code模块(或Text模块,不过Code模块更适合)
- 在模块内容中输入短代码:
[auction_details] - 调整模块的位置和样式,保存即可
这样拍卖信息就会准确显示在你指定的位置,再也不会出现Divi Builder下的位置异常问题了。
内容的提问来源于stack exchange,提问作者Ross
相关产品推荐
相关产品推荐

