如何在Woocommerce Bookings Availability中显示自定义字段
实现Woocommerce Bookings日程区块添加自定义字段的方法
方法一:使用自定义代码(推荐,无需修改核心/模板文件)
借助Woocommerce Bookings提供的过滤器钩子,直接在可用性区块中插入自定义字段内容:
确认自定义字段键名:先确定你设置的“Boat type”“Destination”对应的产品元字段键名(比如
boat_type、destination,如果是用ACF添加的字段,键名就是ACF后台设置的字段标识)。添加代码到站点:将以下代码添加到主题的
functions.php文件,或使用「Code Snippets」这类代码片段插件导入:
add_filter( 'wc_bookings_availability_calendar_day_cell_html', 'append_custom_fields_to_booking_block', 10, 3 ); function append_custom_fields_to_booking_block( $html, $day, $product ) { // 获取自定义字段值 $boat_type = get_post_meta( $product->get_id(), 'boat_type', true ); $destination = get_post_meta( $product->get_id(), 'destination', true ); // 拼接自定义内容HTML $custom_html = ''; if ( $boat_type ) { $custom_html .= '<div class="booking-boat-type"><strong>Boat type:</strong> ' . esc_html( $boat_type ) . '</div>'; } if ( $destination ) { $custom_html .= '<div class="booking-destination"><strong>Destination:</strong> ' . esc_html( $destination ) . '</div>'; } // 将自定义内容插入到区块末尾 if ( !empty( $custom_html ) ) { $html = str_replace( '</div>', $custom_html . '</div>', $html ); } return $html; }
- 样式优化(可选):如果需要调整自定义字段的显示样式,在主题自定义CSS中添加:
.booking-boat-type, .booking-destination { font-size: 0.9em; margin-top: 4px; color: #666; line-height: 1.4; }
方法二:修改模板文件(适合需精细布局的场景)
通过子主题覆盖插件模板,实现更灵活的布局控制:
复制模板文件:在Woocommerce Bookings插件目录中找到
templates/availability-calendar.php,将其复制到你的子主题目录下的woocommerce/bookings文件夹中(没有对应文件夹就手动创建)。编辑模板内容:在代表可用区块的HTML标签内(比如
<div class="wc-bookings-availability-calendar-day available">),插入自定义字段输出代码:
<?php // 获取当前产品的自定义字段值 $boat_type = get_post_meta( get_the_ID(), 'boat_type', true ); $destination = get_post_meta( get_the_ID(), 'destination', true ); ?> <?php if ( $boat_type ) : ?> <div class="booking-boat-type"><strong>Boat type:</strong> <?php echo esc_html( $boat_type ); ?></div> <?php endif; ?> <?php if ( $destination ) : ?> <div class="booking-destination"><strong>Destination:</strong> <?php echo esc_html( $destination ); ?></div> <?php endif; ?>
- 保存文件:修改完成后保存,前端的日程区块就会显示自定义字段内容。
注意事项
- 确保字段键名和你实际设置的一致,若字段值不显示,可检查键名是否匹配。
- 使用代码片段插件添加代码比直接修改
functions.php更安全,避免语法错误导致站点崩溃。 - 模板修改必须通过子主题覆盖,否则插件更新后修改内容会被重置。
内容的提问来源于stack exchange,提问作者Vanbel Manik
相关产品推荐
相关产品推荐

