如何在WPBakery网格模板/短代码中动态获取ACF布尔值?
环境配置
- WordPress插件:WPBakery
- 主题:Highend(含子主题)
已尝试步骤
- 添加ACF字段:已通过Advanced Custom Fields (ACF)成功添加自定义字段,并在postmeta表中验证了值。
- 定位模板文件:在子主题中找到负责HTML输出的文件
vc-gitem-zone.php,并确认修改已在站点生效。
目标
在模板文件中获取ACF字段值(is_lent),以实现样式的条件渲染。
代码片段与问题
if ( ! defined( 'ABSPATH' ) ) { die( '-1' ); } /** * Shortcode attributes * @var $atts * @var $el_class * @var $css * @var $position * @var $bgimage * @var $height * @var $link * @var $url * @var $height_mode * @var $featured_image * @var $img_size * @var $render * @var $content - shortcode content * Shortcode class * @var WPBakeryShortCode_Vc_Gitem_Zone $this */ $el_class = $css = $position = $bgimage = $height = $link = $url = $height_mode = $featured_image = $img_size = $render = $rel = ''; $css_style = $css_style_mini = ''; $image_block = $image = ''; $atts = vc_map_get_attributes( $this->getShortcode(), $atts ); extract( $atts ); // TASK either retrieve post_id or acf "is_lent" for this post // Retrieve current post ID global $post; $post_id = $post->ID; // Retrieve ACF field value $lent = get_field("is_lent", $post_id); echo 'ACF is: ' . $lent; //NOTHING Is being retrieved. if (empty($lent)) { echo "<script>console.log('ACF field \"is_lent\" is empty or not defined for post ID: " . $post_id . "');</script>"; } else { echo "<script>console.log('ACF field \"is_lent\": " . json_encode($lent) . "');</script>"; }; if ( 'no' === $render ) { return ''; } // Code for updating the css and assembling the html.... $output = ''; $output .= '<div class="' . esc_attr( $css_class ) . '"'; $output .= ( empty( $css_style ) ? '' : ' style="' . esc_attr( $css_style ) . '"' ); $output .= '>'; $output .= $image_block . $image; $output .= '<div class="' . esc_attr( $css_class_mini ) . '"' . ( empty( $css_style_mini ) ? '' : ' style="' . esc_attr( $css_style_mini ) . '"' ) . '>' . do_shortcode( $content ) . '</div></div>'; echo $output;
已尝试方案
- 尝试通过post ID获取(硬编码ID时有效,但无法动态获取)。
- 使用
attachment_url_to_postid()(硬编码URL时有效,但无法动态获取URL)。 - 尝试使用
[acf field="is_lent"]短代码,但未得到结果。
预期结果
动态获取ACF布尔值。
实际结果
无法动态获取post ID或ACF值,阻碍了条件渲染的实现。
求助需求
寻求在模板文件中动态获取ACF值的指导或建议。
内容的提问来源于stack exchange,提问作者Shawn GB
相关产品推荐
相关产品推荐

