Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query for Custom Post Type and Multiple Custom Fields

Tags:

sql

wordpress

I am using WP Data Tables to create a table from the SQL DB. In the wordpress backend the example code to use looked like this:

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

Im trying to get custom field values from the post meta. Here is what I have so far...

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 was needed instead of post_id and that I need search for the meta_key. Something like...

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'
like image 465
user2106176 Avatar asked Mar 02 '13 00:03

user2106176


People also ask

How show custom field in custom post type?

You simply need to add the code to your theme template. For example: $value = get_field( 'my_field' ); if($value): echo $value; endif; Just change my_field to the name of your custom field.

How do I get a custom field value in WordPress post?

To add a Custom Field, type in the Key (labeled “Name”) and Value, then click Add Custom Field. After it's added, you can delete or update it from buttons below the Key/Name: After you have used Custom Fields, the keys will form into a dropdown menu for easier selection.


1 Answers

Use an 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'
like image 197
sgeddes Avatar answered Oct 01 '22 22:10

sgeddes