When you are creating a custom loop, generally query_posts or WP_Query is more than enough for the job. But if you want to work on an API project that depends on WordPress tables, then you will need to use custom MySQL queries. Here is a custom MySQL query to get a random post from the WordPress Database.

SELECT DISTINCT p.ID, p.post_title
FROM wp_posts p
WHERE p.post_type = 'post'
AND p.post_status = 'publish'
AND p.post_modified > '2018-09-01 00:00:00'
ORDER BY RAND()
LIMIT 1

This query will return only one row. Then you can use this result to return a json object from your API.

I hope you like this post. If you are interested on more posts like this, please subscribe to our mailing list. Or better, you can follow us on twitter.

Cheers!