I realize how clumsy and inefficient this query is but SQL is not my strong point. I use the following query to pull the latest 8 events from a custom post type called Event Posts. However, I also need to include in those 8 posts any posts which have been stickied. Because of some very complicated client needs which exceed the capabilities of wp_query I've been forced to craft the query by hand and use wpdb to execute it.

Could someone help me add to this query to also grab stickied posts?

SELECT SQL_CALC_FOUND_ROWS *, mt2.meta_value AS start_time, mt3.meta_value AS end_time, mt4.meta_value AS start_date, mt5.meta_value AS event_id, mt6.meta_value AS event_meta, mt7.meta_value AS event_thumb
FROM wp_posts
INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)
INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)
INNER JOIN wp_postmeta AS mt1 ON (wp_posts.ID = mt1.post_id)
INNER JOIN wp_postmeta AS mt2 ON (wp_posts.ID = mt2.post_id AND mt2.meta_key = 'event_start_time')
INNER JOIN wp_postmeta AS mt3 ON (wp_posts.ID = mt3.post_id AND mt3.meta_key = 'event_end_time')
INNER JOIN wp_postmeta AS mt4 ON (wp_posts.ID = mt4.post_id AND mt4.meta_key = 
INNER JOIN wp_postmeta AS mt5 ON (wp_posts.ID = mt5.post_id AND mt5.meta_key = 'event_id')
INNER JOIN wp_postmeta AS mt6 ON (wp_posts.ID = mt6.post_id AND mt6.meta_key = 'event_meta')
INNER JOIN wp_postmeta AS mt7 ON (wp_posts.ID = mt7.post_id AND mt7.meta_key = 'event_thumbnail_url')
AND ( wp_term_relationships.term_taxonomy_id IN (7) )
AND wp_posts.post_type = 'espresso_event'
AND (wp_posts.post_status = 'publish')
AND (wp_postmeta.meta_key = 'event_start_date'
AND (mt1.meta_key = 'event_start_date'
AND CAST(mt1.meta_value AS DATE) >= '" . date('Y-m-d') . "') )
GROUP BY wp_posts.ID ORDER BY CAST(wp_postmeta.meta_value AS DATE) ASC, CAST(mt2.meta_value AS TIME) ASC
LIMIT 0, 8

1 Answer 1


Sticky posts are kept in a serialize array in an option in $wpdb->options with the option_name of sticky_posts. So you will need to pull that option and add an OR to the query.

$sticky = get_option('sticky_posts');

$qry = "... OR {$wpdb->posts}.ID IN (".implode(',',$sticky).")";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.