mysqlwordpressselect

Wordpress Custom Meta Query without wp functions (wo. wp_query())


I have to fetch title, description and attachment out of the wordpress database without wp_query. I can't get how to fetch both, attachments and meta_descriptions at the same time...

This is how my query looks like so far

$query="SELECT post_title, meta_value 
FROM wp_posts p JOIN wp_postmeta pm ON p.ID=pm.post_id 
WHERE post_status='publish' 
AND post_type='page' 
AND post_parent=2330 
AND ( meta_key='_wpseo_edit_description' OR meta_key='_wp_attached_file' ) 
ORDER BY post_date DESC";

This query returns "doubled" results i have to split within a loop

______________________________
| post_title | meta_value    |
|------------|---------------|
|  title 1   | 1349          |
|------------|---------------|
|  title 1   | description 1 |
|------------|---------------|
|  title 2   | 1348          |
|------------|---------------|
|  title 2   | description 2 |
|____________|_______________|

Solution

  • You wlil need to join onto the wp_postmeta table in order to get any of the attached information, such as file attachments or custom fields.

    An example of how to do this:

    SELECT p.*, pm2.meta_value AS featured_image, pm3.meta_value AS wpseo_edit_description, pm4.meta_value AS wp_attached_file
    FROM `wp_posts` p
    LEFT JOIN `wp_postmeta` pm2 ON p.ID = pm2.post_id AND pm2.meta_key = 'wp_attached_file'
    LEFT JOIN `wp_postmeta` pm3 ON p.ID = pm3.post_id AND pm3.meta_key = '_wpseo_edit_description'
    LEFT JOIN `wp_postmeta` pm4 ON p.ID = pm4.post_id AND pm4.meta_key = '_wp_attached_file'
    WHERE p.post_status = 'publish' 
    AND p.post_type = 'page' 
    AND p.post_parent = 2330 
    

    The normal post fields (post title, description, ID, etc) will then be available, along with featured_image, wp_attached_file and wpseo_edit_description.