Not sure what you want to do? do you want an array with all the post titles?
Thread Starter
Jess
(@jessn)
Yeah basically. What I have now will spit out a list like this:
'post-slug' => '1',
'post-slug' => '2',
'post-slug' => '3'
And I want to insert that info into a select menu in a write panel I’m building.
"options" => array(
"1" => "1",
"2" => "2",
"3" => "3"
)
So somehow I want to save the list of posts in a variable, perhaps called $postlist and then echo it like so:
"options" => array(
echo $postlist
)
Of course I don’t even know if that will work but that’s the idea…First I’m just trying to figure out how to save the list of posts into a single variable.
Thread Starter
Jess
(@jessn)
Ah! I did it!
global $post;
$args = array( 'numberposts' => 500, 'offset'=> 1, 'post_type' => 'apples', );
$myposts = get_posts( $args );
$count = 0;
$fruit = array();
foreach( $myposts as $post ) : setup_postdata($post); $count++;
$item = '"'.$count.'" => "'.$post->post_name.'",';
$fruit[] = $item;
endforeach;
Now I can type print_r($fruit); and it will list out the foreach loop results. Yay!
Now what I”m trying to figure out is how to echo that into an options array… This isn’t working:
"options" => array(
print_r($fruit);
)
Now what I”m trying to figure out is how to echo that into an options array… This isn’t working
I think what you want is just this in the foreach:
$fruit[] = $post->post_name;
This will give you an array like this
array('banana','apple');
Which will print as:
Array
(
[0] => banana
[1] => apple
)
This is called an indexed Array.
You can also create arrays this way:
$my_array['fruit'] = 'apple';
$my_array['veggie'] = 'carrot';
Which is the same as:
$my_array = array('fruit' => 'apple', 'veggie' => 'carrot');
and will print as
Array
(
[fruit] => apple
[veggie] => carrot
)
This is called an associative array
http://php.net/manual/en/language.types.array.php
http://www.tizag.com/phpT/arrays.php
I hope this helps.
Thread Starter
Jess
(@jessn)
Ah nice! So much to learn. I redid things a bit thanks to your helpful links and here is what I eventually came up with. The goal was to find a list of posts within a custom post type, store that list into an array, and output the array as options within a select menu.
This parts grabs a list of the posts:
global $post;
$args = array( 'numberposts' => 500, 'offset'=> 1, 'post_type' => 'apples', );
$myposts = get_posts( $args );
$fruit = array();
foreach( $myposts as $post ) : setup_postdata($post);
$fruit[] = $post->post_name;
endforeach;
Then within the code for the select menu in the custom write panel I have:
array(
'name' => 'Type of Fruit',
'desc' => '<b>Select your favorite fruit</b>',
'id' => $prefix . 'fruit_type',
'type' => 'select',
"options" => $fruit,
'std' => ''
),
Super awesome! Thank you for your help!
You’re welcome. Glad you got it resolved.