Better way to list links with different meta values using same meta key?

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 ): ?
    h4Pages 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 ): ?
    h4Pages 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; ?

Topic meta-value get-posts Wordpress

Category Web


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; ?>

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.