0

我的网站上有一些 PHP,其中包含以下代码部分:

'choices' => array ('london' => 'London','paris' => 'Paris',),

目前这个列表是静态的 - 我手动添加到它但是我想动态生成列表

我正在使用以下代码从 WordPress 动态创建一个数组并存储在一个变量中:

function locations() {
   query_posts(array('orderby' => 'date', 'order' => 'DESC' , 'post_type' => 'location'));
   if (have_posts()) :
      while (have_posts()) : the_post();
        $locations = "'\'get_the_slug()'\' => '\'get_the_title()'\',";
      endwhile;
   endif;
   wp_reset_query();
   $locations_list = "array (".$locations."),";
   return $locations_list; // final variable
}

现在,这就是我被困的地方:-)

我现在如何$locations_list分配'choices'

我试过'choices' => $locations_list了,但它使我的网站崩溃了。

非常感谢您的任何指点。

4

3 回答 3

2

呃……什么?

$locations_list = array();
query_posts(...);
while(have_posts()) {
  the_post();
  $locations_list[get_the_slug()] = get_the_title();
}
wp_reset_query();
return $locations_list;

我不知道你在哪里读到你可以从字符串构建变量,但是......你不能(除了eval)所以只需阅读array文档并从那里开始。

于 2013-01-30T16:45:02.083 回答
1

尝试以下: -

function locations() {
query_posts(array('orderby' => 'date', 'order' => 'DESC' , 'post_type' => 'location'));
$locations = array();
if (have_posts()) :
  while (have_posts()) : the_post();
    $locations[get_the_slug()] = get_the_title();
  endwhile;
endif;
wp_reset_query();
return $locations; // final variable
}
于 2013-01-30T16:59:11.477 回答
1

你可以用这个;

<?php
function locations() {
    $locations = array();
    query_posts("orderby=date&order=DESC&post_type=location");
    if (have_posts()) {
        while (have_posts()) {
            the_post();
            $locations[] = get_the_slug() ."#". get_the_title();
        }
    }
    wp_reset_query();
    return $locations;
}

// using
$locations = locations();
foreach ($locations as $location) {
    list($slug, $title) =@ explode("#", $location, 2);
    echo $slug, $title;
}
?>
于 2013-01-30T17:06:30.450 回答