How to order posts in wp_query by a meta_value of the corresponding author

This should give you an idea and I believe this should help you forward.

This query first uses WP_User_Query to fetch all users that are authors registered as premium subscribers and basic subscribers. These users are ordered by meta_value so that premium subscribers are shown first.

A foreach loop return each users’ own ID which can be returned into WP_Query to display posts for each user in order of the meta_value

Here is the complete code. Modify it as needed

<?php
$args = array(
    'who' => 'authors',
    'meta_key' => 'account',
    'orderby' => 'meta_value',
    'order' => 'DESC',
    'meta_query' => array(
        array(
            'key' => 'account',
            'value' => array(1, 2),
        )
    )
);

// The WP_User_Query
$user_query = new WP_User_Query( $args );

// User Loop
if ( ! empty( $user_query->results ) ) {
    foreach ( $user_query->results as $user ) {
        $user->ID;

        $the_query = new WP_Query( 'author=" . $user->ID . "&post_status=publish&post_type=listing' );
        echo '<p>' . $user->display_name . '</p>';
        // The Loop
        if ( $the_query->have_posts() ) {
            echo '<ul>';
            while ( $the_query->have_posts() ) {
                $the_query->the_post();
                echo '<li>' . get_the_title() . '</li>';
            }
            echo '</ul>';
        } 
        /* Restore original Post Data */
        wp_reset_postdata();
    }
}
?>

Leave a Comment