order by issue with query posts and meta value
-
I need to set up a sticky post feature for custom post types. My goal is to sort sticky posts at the top of the list, ordered by priority number in ASC order, followed by non sticky posts sorted by post_date in DESC order.
I created a custom meta field,”_sticky_priority”, that stores a numeric value representing the sticky priority of a post, with lowest number having highest priority. Most posts will not have a sticky priority at all and will not even have a corresponding meta field in the postmeta table.
I first tried query_posts with the following query arguments:
$args = array( 'post_type' => array( 'my_post_type' ), // only show this post type 'orderby' => 'meta_value_num', // numbers only 'meta_key' => '_sticky_priority', 'order' => 'ASC' ); query_posts( $args );
This query only displays the posts that have value in the _sticky_priority meta field but leaves out the rest of non sticky posts. I need a way to include the non sticky posts which will have null for the _sticky_priority meta value.
The following sql query does basically what I need, but how do I acheive this using the wordpress “arguments” syntax in query_post or wp_query?
SELECT * FROM wp_posts LEFT JOIN wp_postmeta ON wp_posts.ID = wp_postmeta.post_id AND wp_postmeta.meta_key LIKE '_sticky_priority' WHERE post_type LIKE 'my_post_type' AND post_status LIKE 'publish' ORDER BY ISNULL(meta_value), meta_value ASC, post_date DESC
- The topic ‘order by issue with query posts and meta value’ is closed to new replies.