juliano.net
juliano.net

Reputation: 8177

Get pages with specific custom field value not working

I have created a custom field in some pages and I need to loop through these pages and print their info. The code I'm using isn't working (the foreach is not looping).

Here's the code:

<?php
        $args = array(
            'meta_key' => 'categoria-pagina',
            'meta_value' => 'programas'
          );

        $pages = get_pages($args);

        foreach ($pages as $page) {
          echo "<p>$page->post_title</p>";
        }

        wp_reset_postdata();
      ?>

And here's the page custom field config (wordpress in portuguese):

What's wrong with it?

Upvotes: 0

Views: 2011

Answers (2)

juliano.net
juliano.net

Reputation: 8177

Solved with this code:

<?php
        $args = array(
            'post_type' => 'page',
            'meta_key' => 'categoria-pagina',
            'meta_value' => 'programas'
          );


        $myPages = new WP_Query($args);
        while ($myPages->have_posts()) : $myPages->the_post(); 
          echo "$post->post_title";
        endwhile;

        wp_reset_postdata();
      ?>

Upvotes: 2

ashaw88
ashaw88

Reputation: 1

<?php
$args = array(
        'meta_key' => 'categoria-pagina',
        'meta_value' => 'programas'
      );
$custom_query = new WP_Query( $args );
// The Loop
if ( $custom_query->have_posts() ) {
while ( $custom_query->have_posts() ) {
    $custom_query->the_post();
    echo '<p>' . get_the_title() . '</p>';
}
} else {
  // no posts found
}
/* Restore original Post Data */
wp_reset_postdata();

That should do the trick for you.

Upvotes: 0

Related Questions