SQL query for custom message type and multiple custom fields

I am using WP Datasheets to create tables from an SQL database. In the wordpress backend, a sample code to use looked like this:

SELECT post_id, post_date
FROM wp_posts
WHERE post_type =  'custom_post_type'
AND post_status =  'publish'

I am trying to get custom field values ​​from metadata. Here is what I still have ...

SELECT post_id, post_date
FROM wp_posts
WHERE post_type =  'custom_post_type'
AND post_status =  'publish'
AND SELECT custom_field_key_1, custom_field_key_2, custom_field_key_3
FROM wp_postmeta
WHERE post_id = post_id

UPDATE:

I found that p.ID is needed instead of post_id and that I need a meta_key search. Sort of...

SELECT p.post_title, 
       p.post_date,
       pm.meta_key = 'custom_field_key'
FROM wp_posts p 
INNER JOIN wp_postmeta pm 
ON p.ID = pm.post_id
WHERE p.post_type = 'custom_post_type'
AND p.post_status = 'publish'
+5
source share
4 answers

Use INNER JOIN:

SELECT p.post_id, 
       p.post_date, 
       pm.custom_field_key_1, 
       pm.custom_field_key_2, 
       pm.custom_field_key_3
FROM wp_posts p 
   INNER JOIN wp_postmeta pm 
       ON p.post_id = pm.post_id
WHERE p.post_type = 'custom_post_type'
   AND p.post_status = 'publish'
+4
source

Assuming standard SQL is supported, you will need something like this (untested):

SELECT w.post_id, w.post_date, m.custom_field_key_1, m.custom_field_key_2, m.custom_field_key_3
FROM wp_posts w, wp_postmeta m
WHERE post_type =  'custom_post_type' AND post_status =  'publish'
AND w.post.id = m.post.id
0
source

.

SELECT p.post_id, p.post_date,
    pm.custom_field_key_1, pm.custom_field_key_2, pm.custom_field_key_3
FROM wp_posts p
JOIN wp_postmeta pm ON p.post_id = pm.post_id
WHERE p.post_type =  'custom_post_type'
AND p.post_status =  'publish'
0

Good, although you updated the answer. I took your example, and I did this:

SELECT p.ID, 
       p.post_title, 
       pm.meta_value as 'value1', 
       pma.meta_value as 'value2'

FROM  wp_posts p 
      INNER JOIN wp_postmeta AS pm  ON pm.post_id  = p.ID
      INNER JOIN wp_postmeta AS pma ON pma.post_id = p.ID

WHERE
      pma.meta_key = 'custom_field_key_1' AND
      pm.meta_key = 'custom_field_key_2' AND

      p.post_type = 'your_post_type' AND 
      p.post_status = 'publish'

So, here I use an alias ASfor values ​​located in the same table, INNER JOINfor wp_postmetaand post_idthat’s all.

References: Several internal members of the same table

Through this, you will get an array with messages and custom fields you selected:

array(1) {
    [0]=> object(stdClass)#341 (4) {
          ["ID"]=>    string(1) "1123"
          ["post_title"]=>  string(15) "Your post title"
          ["custom_field_key_1"]=> string(12) "Your value 1 "
          ["custom_field_key_2"]=> string(29) "Your value 2"
}

You can add as many aliases and meta_key as you need. Hope this help!

0
source

All Articles