I am trying to create a SQL Query that will output the Woocommerce products in my MySQL Database that do not have a featured image assigned to it. As Woo is based on Wordpress, I'm not sure where to get the information from but it looks as if I will need to join some tables up.
Has anyone out there had experience with this? I have 500 products and all need to have a Featured Image. I am going through them randomly and assigning each product one, but I need to see how many are left to do and which ones need to be done.
I am unable to sort the Products by Featured Image in the Woocommerce backend so I am hoping it can be achieved via SQL Query.
It looks as if I have found the right query. It joins some tables to give me a list of all products and featured images. I can then sort this list and see what products have NULL Featured Images. The SQL Query I used is below in case it helps somebody:
SELECT p.ID, p.post_title, pm.*
FROM wp_posts p
LEFT JOIN wp_postmeta pm ON p.ID = pm.post_id
AND pm.meta_key = '_thumbnail_id'
WHERE p.post_type IN ( 'product' )
This would be my query. It will return all post id's ( same as product id's ) that have no image
select ID FROM wp_posts WHERE ID NOT IN (select post_id from wp_postmeta WHERE meta_key="_thumbnail_id") AND post_type="product"
Create a View called Products_List
:
SELECT
`wptt_posts`.`post_title` AS `post_title`,
`wptt_posts`.`post_name` AS `post_name`,
`wptt_postmeta`.`meta_value` AS `meta_value`,
`wptt_posts`.`ID` AS `ID`
FROM
(
`wptt_posts`
JOIN `wptt_postmeta` ON (
(
`wptt_posts`.`ID` = `wptt_postmeta`.`post_id`
)
)
)
WHERE
(
(
`wptt_posts`.`post_type` = 'product'
)
AND (
`wptt_postmeta`.`meta_key` = '_sku'
)
)
ORDER BY
`wptt_postmeta`.`meta_value`
Then create another query using Products_List
above:
SELECT
Products_List.ID as "Product ID",
Products_List.meta_value as "SKU",
Products_List.post_name as "Product Name",
Products_List.post_title as "Product Title",
'NO' AS "HAS FEATURED Image"
FROM
Products_List
WHERE
ID NOT IN (
SELECT
Products_List.ID
FROM
Products_List
LEFT JOIN wptt_postmeta ON Products_List.ID = wptt_postmeta.post_id
WHERE
wptt_postmeta.meta_key = '_thumbnail_id'
)
UNION
SELECT
Products_List.ID as "Product ID",
Products_List.meta_value as "SKU",
Products_List.post_name as "Product Name",
Products_List.post_title as "Product Title",
'YES' AS "HAS FEATURED Image"
FROM
Products_List
LEFT JOIN wptt_postmeta ON Products_List.ID = wptt_postmeta.post_id
WHERE
wptt_postmeta.meta_key = '_thumbnail_id'
Another possibility that does not use a NOT IN :
SELECT p.ID, p.post_title
FROM `wp_posts` as p LEFT OUTER JOIN wp_postmeta pm ON (p.ID=pm.post_id AND pm.meta_key = '_thumbnail_id')
WHERE p.post_type = 'product'
AND
(meta_key IS NULL OR meta_value = "")