Best practice to limit results in get_row()?

This is my query to check if a title exists (it's in a loop, therefore [$i]).

$wpdb-get_row("SELECT * FROM wp_posts WHERE post_title = '" . $titles_arr[$i] . "'", 'ARRAY_A');

Anyway, I would like to know how to use LIMIT 0,1000 to query only the last 1000 added posts to the database when using get_row() function.

Any idea?

Topic get-row mysql wpdb database query Wordpress

Category Web


This is essentially a SQL question. The only possible WordPress related component would be if you were asking about database structure, which is in the Codex. Or you could just look at the database itself.

The post ID is incremented and never duplicated. The highest IDs are the last added. The query is simple.

SELECT * 
FROM {$wpdb->posts} 
WHERE post_title = '{$titles_arr[$i]}'
ORDER BY {$wpdb->posts}.ID DESC
LIMIT 0,1000

Please note that I used $wpdb->posts instead of hard-coding the table name. Your query will break on a site that has a different prefix than wp_ and on multisite (I am pretty sure).

Note that the $wpdb->posts hold a lot of information besides simply post post types. If you specifically want just post post types you will need to add a further condition.

SELECT * 
FROM {$wpdb->posts} 
WHERE post_title = '{$titles_arr[$i]}'
AND {$wpdb->posts}.post_type = 'post'
ORDER BY {$wpdb->posts}.ID DESC
LIMIT 0,1000

Still further conditions could be required to prevent the results from including 'draft' or 'pending' posts, or 'revisions', or a number of other things.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.