1

I've run a get_posts query in WordPress and need to pull a pair of custom fields and get all of them into one array. The get_posts query provides an array of posts, but when I use foreach to access the custom fields, I end up with separate arrays for each result.

The Query

$c_query = get_posts(
                    array(
                        'post_type' => 'page',
                        'paged' => get_query_var('paged'),
                        'order' => 'ASC',
                        'orderby' => 'meta_value',
                        'meta_key' => 'concert_date',
                        'meta_query' => array(

                            array(
                                'key'   => '_wp_page_template', 
                                'value' => array('rock.php', 'pop.php', 'jazz.php'),
                                'compare' => 'IN'
                            )
                            array(
                              'key'   => 'concert_date'
                              'value'  => date('m/d/Y')
                            )

                         )
                    )
                );  

Foreach

To access the concert date, I used foreach:

foreach($c_query as $post) : setup_postdata($post); 

        $c_query['concert_date'] = $concert_date = get_post_meta(get_the_ID(),
 'concert_date', true);
        $c_query['concert_city'] = $concert_date = get_post_meta(get_the_ID(),
 'concert_city', true); 

endforeach;

and the result pulls the correct data, but I get separate arrays for each concert date and city pair (because of foreach):

Resulting Arrays

 Array ( [0] => 01-11-2012 [1] => New York) 
 Array ( [0] => 03-23-2013 [1] => Boston) 
 Array ( [0] => 06-09-2014 [1] => London) 

What can I do to get these result arrays into one big array? Trying to get an array of the concert date and city pairs.

1

You can alter your foreach loop as following to get concert date and city pair in single multidimentional array as following.

$concert_query = array();
$i = 0;

foreach($c_query as $post) : setup_postdata($post); 

    $concert_query[$i]['concert_date'] = get_post_meta(get_the_ID(), 'concert_date', true);
    $concert_query[$i]['concert_city'] = get_post_meta(get_the_ID(), 'concert_city', true); 
    $i ++;
endforeach;

print_r($concert_query);
1

You should not have to setup post data on $post each time. You already have the post ID and get_post_meta() does not depend on the $post variable.

$concerts = array();

foreach ( $c_query as $concert ) {
    $concerts[] = array(
        'concert_date' => get_post_meta( $concert->ID, 'concert_date', true ),
        'concert_city' => get_post_meta( $concert->ID, 'concert_city', true ),
    );
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.