To order queries by the current user ID in WordPress, you can use the get_current_user_id()
function to retrieve the current user’s ID and then include it in your custom query. Here’s an example using the WP_Query
class to retrieve posts ordered by the current user ID:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
// Get the current user ID $current_user_id = get_current_user_id(); // Set up the query arguments $args = array( ‘post_type’ => ‘post’, // Change ‘post’ to your custom post type if applicable ‘posts_per_page’ => –1, // Display all posts ‘orderby’ => ‘author’, // Order by author (user ID) ‘order’ => ‘ASC’, // Order in ascending order ‘author’ => $current_user_id, // Show posts only by the current user ); // Instantiate the query $custom_query = new WP_Query( $args ); // Check if there are posts if ( $custom_query–>have_posts() ) : // Start the loop while ( $custom_query–>have_posts() ) : $custom_query–>the_post(); // Display post content or other details the_title(); the_content(); endwhile; // Restore global post data wp_reset_postdata(); else : // No posts found echo ‘No posts found’; endif; |
The issue with this snippet is it only gives the post of the current user ID and not posts by other users.
the following snippet lists down posts and order by the current user so that the current user post appears first and then the other post, you can use the same for other posts’ post_type as well.
1 2 3 4 5 6 7 |
$posts = $wpdb–>get_results( “SELECT ID, post_title FROM $wpdb->posts WHERE post_status = ‘publish’ AND post_type =”page“ ORDER BY CASE WHEN user_id = ‘get_current_user_id()’ THEN 1 ELSE 2 END” ); |
This example assumes that you want to retrieve posts (you can change ‘post_type’,post_status to your custom post type and status if needed) authored by the current user and order them by user ID in ascending order.