I have a custom taxonomy "length" with 3 values ['long', 'medium', 'short'] I have attached this taxonomy to attachments (using CPT UI)

Upon viewing the taxonomy I can see that I have successfully added 'long' to an image as it shows "count = 1"

However my query is returning no records.

    [post_type] => attachment
    [post_mime_type] => image
    [post_status] => inherit
    [posts_per_page] => -1
    [meta_query] => Array
        [0] => Array
                [key] => length
                [value] => Array
                        [0] => 26
                [compare] => IN



If I remove the meta_query it does return all images. I have confirmed that the ID for the 'long' taxonomy record is 26. I can see in the wp_postmeta that the values exist for the correct records.

the request query is:

SELECT   wp_posts.* FROM wp_posts  INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) WHERE 1=1  AND (wp_posts.post_mime_type LIKE 'image/%')  AND ( 
( wp_postmeta.meta_key = 'length' AND CAST(wp_postmeta.meta_value AS CHAR) IN ('26') )
) AND wp_posts.post_type = 'attachment' AND ((wp_posts.post_status = 'inherit')) GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC 

I can see the problem is that the meta_value is stored as a serialized object and that:

 wp_postmeta.meta_key = 'length' AND CAST(wp_postmeta.meta_value AS CHAR) IN ('26')

will never be true. I can write a custom sql query to fix this, but, I am wondering if there is something I am missing with the meta query?

  • if I use LIKE instead of IN it does return btw. however this will match any 26 value. 126, 226 etc – Kudos Aug 5 '16 at 7:15

Why you are querying for meta query if your length is taxonomy? Replace meta_query with tax_query in your query and it should start working.

  • Thanks Krysztof, I did try this. However I have realised the issue is that ACF is not saving the term as it should for media. – Kudos Aug 5 '16 at 7:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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