Using custom SQL with WP_Query class
-
Hi,
So I’m trying to understand how the WP_Query class works exactly. I’m using a theme that already uses it to display elements on a page. Although, I need to add some conditions to it and I don’t know how to do it. I need to add left joins on the users and usermeta tables.
I was able to get the raw query that WP_Query generates, which is:
SELECT SQL_CALC_FOUND_ROWS dv_posts.ID FROM dv_posts WHERE 1=1 AND dv_posts.post_type = ‘estate_agent’ AND ((dv_posts.post_status = ‘publish’)) ORDER BY RAND() LIMIT 0, 200
Although, I tried throwing the above SQL query directly as the wp_query class parameter and it didn’t work. My end query needs to look like this:
SELECT *
FROM dv_posts
LEFT JOIN dv_postmeta ON dv_postmeta.post_id = dv_posts.ID AND dv_postmeta.meta_key LIKE ‘user_meda_id’
LEFT JOIN dv_users ON dv_users.ID = dv_postmeta.meta_value
LEFT JOIN dv_usermeta um1 ON um1.user_id = dv_users.ID AND um1.meta_key LIKE ‘package_activation’
LEFT JOIN dv_usermeta um2 ON um2.user_id = dv_users.ID AND um2.meta_key LIKE ‘package_id’
WHERE 1=1
AND dv_posts.post_type = ‘estate_agent’
AND ((dv_posts.post_status = ‘publish’))
AND (dv_users.ID IS NULL OR (um2.meta_value IS NOT NULL AND CURDATE() <= DATE_ADD(um1.meta_value, INTERVAL 1 MONTH)))
ORDER BY RAND()
LIMIT 0, 200The reason why I need to keep using wp_query is because the template is using the global variables generated by wp_query and I think it would be complicated to change that.
Thanks in advance
- The topic ‘Using custom SQL with WP_Query class’ is closed to new replies.