Is there a way to pass an array as a variable out of the wp_query loop? I want to collect post meta from the four posts — next week and the following three weeks. To keep the code clean, I thought it'd be easiest to capture the variable and use the data later in the form.
// Capture next week's week number
$nextweek = date("W", strtotime( "+1 week"));
// Query all custom post types
$menu_args = array(
'post_type'=>'single_menu',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC'
);
$menu = new WP_Query( $menu_args ); if ( $menu->have_posts() ) : while ( $menu->have_posts() ) : $menu->the_post();
// Get custom fields
$menuids = array( get_post_field( 'week', $post->id ) );
$titles = array( get_post( $post->id )->post_title );
$choosefrom = array( get_post_field( 'menu_listing', $post->id ) );
$selection = array( get_post_field( $checkout_menu, $post->id ) );
// Create new array with custom fields
$result = array();
foreach ( $menuids as $id => $menuid ) {
$result[$menuid] = array(
'title' => $titles[$id],
'offering' => $choosefrom[$id],
'menu' => $selection[$id],
'delivery' => 0,
);
}
// Return the arrays for specified weeks
for ($i = $nextweek; $i<$nextweek+4; $i++) {
if ( $result[$menuid] == $result[$i] ) {
print_r( $result );
}
}
endwhile;
endif;
print_r() returns the correct results, my $results array for the next four weeks. However, when I create a variable and call it outside the loop, like below, I only get the last/fourth $result in the array:
for ($i = $nextweek; $i<$nextweek+4; $i++) {
if ( $result[$menuid] == $result[$i] ) {
$payload = $result;
}
}
endwhile;
endif;
print_r( $payload );
Same thing happens when I create a new array like so:
$payload = array();
for ($i = $nextweek; $i<$nextweek+4; $i++) {
if ( $result[$menuid] == $result[$i] ) {
$payload[] = $result;
}
}
endwhile;
endif;
print_r( $payload );
If I concatenate the variable like $payload .= $result;, I get ArrayArrayArrayArray returned.
I know I can echo the form inside loop, but would rather take the array as a data variable if at all possible. Am I missing something easy?
$postsproperty ...? codex.wordpress.org/Class_Reference/…endwhileandendifloop. How might the$postsproperty help me achieve this?payload = array();OUTSIDE of the loop. You helped me to stop over-thinking it.