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 に答える