Paul Chris Jones's coding blog
PHP
JS

MySQL queries for Wordpress

25th March 2020

Here are a few queries I've found helpful when working with Wordpress databases.

Note: In the examples below, the tables begin with the prefix '123_'. If you use any of the examples, make sure to change '123_' to the prefix of your own Wordpress tables.

MySQL query to get the most recent version of all Wordpress posts

SELECT * FROM 123_posts
WHERE post_status = 'publish'
AND post_content != ""
ORDER BY post_date DESC

MySQL query to get Wordpress posts by tag

SELECT
    p.id AS Post_ID,
    p.post_name AS Post_name,
    t.`name` AS Tag
FROM
    123_posts p
JOIN 123_term_relationships tr ON
    (p.`id` = tr.`object_id`)
JOIN 123_term_taxonomy tt ON
    (
        tt.`term_taxonomy_id` = tr.`term_taxonomy_id` AND tt.`taxonomy` = 'post_tag'
    )
JOIN 123_terms t ON
    (tt.`term_id` = t.`term_id`)
WHERE
    t.name = "insert tag name here"
GROUP BY
    p.id

MySQL query to get Wordpress posts by category

SELECT
    p.id AS Post_ID,
    p.post_name AS Post_name,
    c.name AS Category
FROM
    123_posts p
JOIN 123_term_relationships cr ON
    (p.`id` = cr.`object_id`)
JOIN 123_term_taxonomy ct ON
    (
        ct.`term_taxonomy_id` = cr.`term_taxonomy_id` AND ct.`taxonomy` = 'category'
    )
JOIN 123_terms c ON
    (ct.`term_id` = c.`term_id`)
WHERE
    c.name = "insert category name here"
GROUP BY
    p.id

MySQL query to get the comments for a specific Wordpress post

SELECT
    123_posts.ID,
    comment_author,
    comment_author_email,
    comment_date,
    comment_content
FROM
    123_comments
JOIN 123_posts ON ID = comment_post_ID
WHERE
    comment_approved = '1' AND post_status = 'publish' AND 123_posts.ID = 8950
ORDER BY
    comment_date
DESC

MySQL query to change the status of a Wordpress post

UPDATE
    wp_krnp_posts
SET
    post_status = 'private' # or 'publish' or 'draft'
WHERE
    123_posts.ID = 1852

MySQL query to get a list of featured images

SELECT
    p1.ID,
    p1.post_title,
    wm2.meta_value AS Featured_image
FROM 
    123_posts p1
LEFT JOIN 
    123_postmeta wm1
    ON (
        wm1.post_id = p1.id 
        AND wm1.meta_value IS NOT NULL
        AND wm1.meta_key = "_thumbnail_id"              
    )
LEFT JOIN 
    123_postmeta wm2
    ON (
        wm1.meta_value = wm2.post_id
        AND wm2.meta_key = "_wp_attached_file"
        AND wm2.meta_value IS NOT NULL  
    )
WHERE
    p1.post_type="post"
ORDER BY 
    p1.post_date DESC

Leave a comment