Wordpress ACF 将变量作为值传递给 args 数组

Wordpress ACF passing a variable as a value into args array

我正在尝试创建动态 posts 布局。在后端,我有一个字段,我可以在其中输入要传入的 post 集合的 slug。

$subfield 值为食谱。出于某种原因,当我写 'post_type' => $subfield 时它不起作用。它仅在我对其进行硬编码时才有效。当我将它作为值传递给 'post_type'

时,关于为什么我的 $subfield 变量为空的任何见解
<?php 



if ( 
get_row_layout() == 'list_posts' ) {

// $subfield = the_sub_field( 'custom_post_type' );
// this variable has a string value of recipe in the backend

    
$args = array(
  'post_type'   => 'recipe' //works when hardcoded, not when $subfield is passed
 );


 $the_query = new WP_Query($args );

 if (
 $the_query->have_posts() )
 :while (
 $the_query->have_posts() )
 : $the_query->the_post();
 ?>

  <a href="<?php echo the_permalink();?>">
     <?php echo the_title();?>
  </a>

  

  <?php wp_reset_postdata();
      endwhile;
      endif;
    } 

  ?>

根据ACF documentthe_sub_field() 显示来自转发器或灵活内容字段循环的特定子字段值的值。这个函数本质上和echo get_sub_field()是一样的。因此,它不会 return $subfield 变量的期望值。让我们使用 get_sub_field() 代替:

$subfield = get_sub_field( 'custom_post_type' );

在 WordPress 世界中有一个隐含的约定:显示值的函数名称将以 the_ 开头,而 return 值的函数名称将以 [= 开头16=].