检索数组中的变量

Retrieve variable within an Array

我正在尝试通过函数 query_posts 在 Wordpress 页面模板中创建特定类别的帖子列表。 如果我直接在 query_posts' 数组值中输入 category_name 值(例如 'category_name' => 'france-category'),它工作正常。

但我希望能够通过页面编辑器中的自定义字段来定义类别。

get_field("custom-field") 函数检索我在自定义字段中设置的值。 所以我尝试将我的自定义字段的值放入一个变量中,然后检索数组中的变量值:

<?php
$category = get_field("france-category");

// The Query
query_posts( array ( 'category_name' => 'echo $category' ) ); 

// The Loop
while ( have_posts() ) : the_post();
    the_title();
endwhile;

// Reset Query
wp_reset_query();
?>

但出于某种原因,这不起作用。不能在数组中使用变量吗?或者谁能​​告诉我我还做错了什么?

在您的代码中,尝试将 'echo $category' 替换为 $category。因为你不需要使用echo!因为 $category 字段将具有您可能已经获取的值。所以你可以传递那个变量。

所以,而不是这一行:

query_posts( array ( 'category_name' => 'echo $category' ) ); 

试试这个:

query_posts( array ( 'category_name' => $category ) );