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



我正在尝试创建一个动态的posts布局。在后台,我有一个字段,我在其中输入要传递的后期收集的片段

$subfield值为配方。出于某种原因,当我写"post_type"=>子字段不起作用。只有当我对其进行硬编码时,它才有效。当我将$subfield变量作为值传递给"post_type"时,它为什么为空的任何见解

<?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文档:the_sub_field()显示中继器或灵活内容字段循环中特定子字段值的值。该函数与echo get_sub_field()基本相同。因此,它不会将期望值返回给$subfield变量。让我们改用get_sub_field()

$subfield = get_sub_field( 'custom_post_type' );

WordPress世界中有一个隐含的约定:显示值的函数的名称将以the_开头,返回值的函数名称将以get_开头。

最新更新