WordPress: Get post by title
Not entirely obvious from what’s our there…
|
1 2 3 4 5 6 |
<code>$sql = sprintf( "SELECT * from {$wpdb->posts} WHERE post_title='%s' AND ( post_status <> 'trash' AND post_status <> 'inherit' AND post_status <> 'auto-draft' )", addslashes( $title ) ); $matching_post = get_object_vars( $wpdb->get_row($sql) ); </code> |
I chose to use get_object_vars rather than passing the ARRAY_A second param as the later misses out on some escaping I think from what I’ve seen of it’s usage in the code. Does anyone know more about this point?
Also it should be mentioned that this is probably an expensive operation for large sites. You’d be much better filtering by an indexed db fiels such as post_name (ie the slug).
I couldn’t use this in my case as the later adds a number onto the sanitized title to make it unique if the title occurs on other posts (such as trashed ones).


