1

This works, but I will need it to make 8 different lists on the page, using same meta key but 8 different meta values. Is there a more efficient way to achieve this rather than repeating the same code 8 times?

<?php 
$posts = get_posts(array(
    'numberposts'   => -1,
    'post_type'     => 'page',
    'meta_key'      => 'my_meta_key',
    'meta_value'    => 'meta_value_1'
));
if( $posts ): ?>
    <h4>Pages with Meta Value 1:</h4>
    <ul>
    <?php foreach( $posts as $post ): 
        setup_postdata( $post );
        ?>
        <li>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        </li>
    <?php endforeach; ?>
    </ul>
    <?php wp_reset_postdata(); ?>
<?php endif; ?>
<?php
$posts = get_posts(array(
    'numberposts'   => -1,
    'post_type'     => 'page',
    'meta_key'      => 'my_meta_key',
    'meta_value'    => 'meta_value_2'
));
if( $posts ): ?>
    <h4>Pages with Meta Value 2:</h4>
    <ul>
    <?php foreach( $posts as $post ): 
        setup_postdata( $post );
        ?>
        <li>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        </li>
    <?php endforeach; ?>
    </ul>
    <?php wp_reset_postdata(); ?>
<?php endif; ?>
3
  • Have you looked into custom php functions, with meta value as an input argument, it might help here.
    – birgire
    May 22, 2022 at 20:11
  • 1
    Thanks @birgire - I'm new to WP and I'm learning as I go. I'll see if this helps!
    – KSechrist
    May 22, 2022 at 20:16
  • Also avoid -1, use eg some upper limit on returned posts.
    – birgire
    May 22, 2022 at 20:26

1 Answer 1

0

I don't think this is what birgire intended (thank you though!) but this is my revised code after doing some research. Much shorter, and meets my needs, but I'd still like eyes on it just to be sure I'm not doing something stupid. The NOT IN array '' was to only retrieve pages that have a meta_value set for this key - it worked perfectly, but maybe there's a better way to do this?

<?php 
$posts = get_posts(array(
    'numberposts'   => 500,
    'post_type'     => 'page',
    'meta_key'      => 'my_meta_key',
    'meta_value' => array(''),
    'meta_compare' => 'NOT IN',     
    'orderby'   => 'meta_value',
    'order'     => 'ASC'
));
if( $posts ): ?>
    <h4>Posts with a Value in my_meta_key:</h4>
    <table>
    <?php foreach( $posts as $post ): 
        setup_postdata( $post );
        ?>
        <tr>
            <td><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></td>
            <td><?php echo get_post_meta( get_the_ID(), 'my_meta_key', true ); ?></td>
        </tr>
    <?php endforeach; ?>
    </table>
    <?php wp_reset_postdata(); ?>
<?php endif; ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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