I’m trying to make a custom query to pick up posts (they’re really products) from wordpress, where don’t have a meta_query named ‘custom_code’.
I’m trying:
SELECT DISTINCT p.ID
FROM
wp_posts p
LEFT JOIN wp_postmeta pm ON p.ID = pm.post_id
WHERE
p.post_type = 'product'
AND ( p.post_status = 'publish' OR p.post_status = 'draft' )
AND pm.meta_key = 'custom_code' AND pm.meta_key IS NULL
I tried with NOT EXISTS, but sql returns error:
SELECT DISTINCT p.ID
FROM
wp_posts p
LEFT JOIN wp_postmeta pm ON p.ID = pm.post_id
WHERE
p.post_type = 'product'
AND ( p.post_status = 'publish' OR p.post_status = 'draft' )
AND NOT EXISTS (
select * from wp_postmeta as pm2
where pm2.meta_key = 'custom_code'
)
NOTE: I need to get such posts with status ‘publish’ as posts with status ‘draft’.
ERROR returned:
Keyword unrecognized. (Near “NOT”, at position 193)
Keyword unrecognized. (Near “EXISTS”, at position 197)
Symbol (token) unexpected. (Near “(” at position 204)
CURRENT POINT
I did with WordPress API, and it works, but I need to add a LEFT JOIN to also get products with name like the name of each product returned by sentence below. This is the sentence:
$args = array(
'posts_per_page' => -1,
'post_type' =>'product',
'post_status' => 'publish,draft',
'meta_query' => array(
array(
'key' => 'custom_code',
'compare' => 'NOT EXISTS'
)),
);
$posts_array = get_posts( $args );
Any help?
Thanks in advance.
Have you tried something like this
NOTE
Use this code to print query
This is how a query with
NOT EXITSTS
could be:or, using
LEFT JOIN
: