1

I want to grab all of the Wordpress pages that include the meta key 'basePrice', regardless of the meta value.

When I try to do a simple get_pages(), an empty array is returned. Acording to the Wordpress docs, it states that meta_value requires meta_key to work, but not the other way around, so it should work?

$basePrices = get_pages(array(
    'meta_key' => 'basePrice'
));

How can I get all pages that have a meta key called 'basePrice' in my array?

Lee
  • 4,187
  • 6
  • 25
  • 71

1 Answers1

0

First, you should use a WordPress query object for these kind of complex queries. That'll give you more arguments to play with.

So you could do:

// Let's prepare our query:
$args = array(
   'post_type' => 'page',
   'posts_per_page' => -1,
   'meta_query' => array(
        array(
           'key' => 'basePrice',
           'compare' => 'EXISTS'
        ),
   )
);
$the_query = new WP_Query( $args );

// Array to save our matchs:
$pages = array();

// The Loop
if ( $the_query->have_posts() ) {

    while ( $the_query->have_posts() ) {

         // Let's take what we need, here the whole object but you can pick only what you need:
         $pages[] = $the_query->the_post();

    }

    // Reset our postdata:
    wp_reset_postdata();
}

That should work just fine.

The other way using get_pages() is to get all pages -> loop them -> create a get_post_meta() if statement. If there is a value you add the current page to your array. But as you can imagine, you have to load all pages whereas you shouldn't have to.

Hope that helps,

2Fwebd
  • 2,005
  • 2
  • 15
  • 17