Using raw query instead of meta_query
-
Some years ago, I purchased a premium theme from a very well know market. Only recently I found an unwanted behavior in one of its widgets.
The widget is an event widget: it displays a certain number of rows containing a rectangle with the date, the title of the event, etc.
Problem is I found the widget doesn’t display the events based on the event date, but, instead, it uses the publish date; so, for example, if today I post an event in 1984, it displays this event at the top of the list.
I found the code involved is the following:
<?php $args = array( 'post_type' => 'event', 'post_per_page' => $number, 'showposts' => $number ); $latest_events = new WP_Query($args); if ($latest_events->have_posts()): global $post; ?> <?php while($latest_events->have_posts()): $latest_events->the_post(); $event_month = get_post_meta($post->ID, 'core_event_month', true); $event_day = get_post_meta($post->ID, 'core_event_day', true); $event_time = get_post_meta($post->ID, 'core_event_time', true); $event_location = get_post_meta($post->ID, 'core_event_location', true); ?>
As you can see, the developer saves in
wp_postmeta
month, day and time (luckily, year too), but not a usefultimestamp
. Month is a string (eg. “November”), day and year are numbers. I don’t care about time at the moment.I tried to change the
WP_Query
$args in any possible way, but I could not find one that could order the results by date.Finally, I decided to create an hardcoded SQL version of the query, this one:
SELECT wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta AS meta1 ON ( wp_posts.ID = meta1.post_id ) ? INNER JOIN wp_postmeta AS meta2 ON ( wp_posts.ID = meta2.post_id ) ? INNER JOIN wp_postmeta AS meta3 ON ( wp_posts.ID = meta3.post_id ) WHERE wp_posts.post_type = 'event' AND wp_posts.post_status = 'publish' AND meta1.meta_key = 'core_event_month' AND meta1.meta_value IN ('November','December') AND meta2.meta_key = 'core_event_day' AND meta2.meta_value >= 4 AND meta3.meta_key = 'core_event_year' AND meta3.meta_value = 2019 GROUP BY wp_posts.ID ORDER BY STR_TO_DATE(CONCAT(meta1.meta_value," ",meta2.meta_value," ",meta3.meta_value), "%M %d %Y") DESC
The idea in the last line is to concat the meta fields values to build a string representing a date, so that I can sort events by date.
Now, I have a couple of questions:
1. is it possible to create a
WP_Query
version of my query?
2. is there any way to use my query in the context of the code I posted? How?Thanks anybody, any help is appreciated
- The topic ‘Using raw query instead of meta_query’ is closed to new replies.