WORDPRESS · BANCO-DE-DADOS
How to List Posts by Category in WordPress Using SQL
Learn how to use an SQL query to list posts by category in WordPress. This guide includes instructions on how to find the ID of the desired category.
Here is a query that helps in understanding the link between WordPress tables and depending on the case, it can be very useful to list posts by category via sql.
SELECT DISTINCT ID, post_title, post_name, guid, post_date, post_content
FROM wp_posts AS p
INNER JOIN wp_term_relationships AS tr ON (
p.ID = tr.object_id
)
INNER JOIN wp_term_taxonomy AS tt ON (
tr.term_taxonomy_id = tt.term_taxonomy_id
AND taxonomy = 'category' AND tt.term_id
IN ( 16 )
)
ORDER BY id DESC
Change ID 16 to the ID number of the category you want to search.
Don’t know how to find the category ID? Leave your comment.
Thx!
Revisited in November 2026
The post left a question hanging: how to find the category ID. This query lists the categories with each one’s ID
(replace wp_ with your table prefix):
SELECT t.term_id, t.name, t.slug
FROM wp_terms AS t
INNER JOIN wp_term_taxonomy AS tt ON t.term_id = tt.term_id
WHERE tt.taxonomy = 'category'
ORDER BY t.name;
Two adjustments to the main query that I would make today:
- It returns posts in any state: published, drafts and the ones in the trash. To see only published posts, add
WHERE p.post_type = 'post' AND p.post_status = 'publish'before theORDER BY. - The
guidcolumn isn’t the post’s address. It’s an identifier recorded when the post is created, and it doesn’t change if the domain or the permalink changes.
If WP-CLI is installed on the server, you can get the same list without SQL:
wp post list --cat=16 --fields=ID,post_title,post_date Who writes this
Eduardo Lira
Software developer in Rio de Janeiro. I started this blog in 2012, in technical support at a hosting company, writing down the fixes for the problems that came up every day. Today I work at Sofis Tecnologia, on critical healthcare systems and SQL Server database migrations.