I have some PHP on my site which contains the following portion of code:
'choices' => array ('london' => 'London','paris' => 'Paris',),
Currently this list is static - I manually add to it however I want to generate the list dynamically .
I'm using the following code to create an array dynamically from WordPress & store in a variable:
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
}
Now, this is where I'm stuck :-)
How do I now assign $locations_list
to 'choices'
?
I tried 'choices' => $locations_list
but it crashed my site.
Many thanks for any pointers.
Erm... whut?
$locations_list = array();
query_posts(...);
while(have_posts()) {
the_post();
$locations_list[get_the_slug()] = get_the_title();
}
wp_reset_query();
return $locations_list;
I don't know where you read that you could build variables from a string, but... you can't (except eval
) so just read the array
docs and go from there.
Try following:-
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
}
You can use this;
<?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;
}
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.