WordPress如何筛选元值达标文章并按字母排序且排除指定文章?
Hey there! Let's fix your query step by step. Based on your requirements, here's how to get the posts you want:
First, let's break down what we need to accomplish:
- Exclude Post 1 entirely from results
- Filter posts where the
ratingmeta value is equal to or higher than Post 1's rating (we'll fetch this dynamically so it stays flexible if Post 1's rating changes) - Sort the remaining posts alphabetically by their title
Here's the working code snippet:
// First, fetch Post 1 to get its rating value as our threshold $post1 = get_posts(array( 'post_type' => 'post', 'title' => 'post 1', // Match Post 1's exact title 'numberposts' => 1, 'meta_key' => 'rating' )); $min_rating = 0; if (!empty($post1)) { $min_rating = get_post_meta($post1[0]->ID, 'rating', true); } // Now pull the desired posts $my_posts = get_posts(array( 'post_type' => 'post', 'numberposts' => -1, 'post_parent' => $parent_id, // Keep your existing parent ID filter 'post__not_in' => !empty($post1) ? array($post1[0]->ID) : array(), // Exclude Post 1 'meta_query' => array( array( 'key' => 'rating', 'value' => $min_rating, 'compare' => '>=', // Grab posts with rating equal or higher than Post 1's 'type' => 'numeric' // Critical for correct number comparison ) ), 'orderby' => 'title', // Sort alphabetically by post title 'order' => 'ASC' ));
Key details to note:
- We fetch Post 1's rating dynamically instead of hardcoding
1—this way, if Post 1's rating ever updates, the query adapts automatically. post__not_inensures Post 1 is excluded from your results.- Adding
type => 'numeric'to the meta query makes sure the rating comparison works as expected (no string-based sorting issues). orderby => 'title'andorder => 'ASC'sorts your posts alphabetically from A-Z.
If you already know Post 1's ID, you can simplify the code by skipping the initial get_posts call and directly fetching its rating:
$min_rating = get_post_meta(POST1_ID, 'rating', true); // Replace POST1_ID with the actual ID of Post 1
内容的提问来源于stack exchange,提问作者Joel Rosen
相关产品推荐
相关产品推荐

