How can I check if post with name for example Weather exists? If not I want to create it.
function such_post_exists($title) {
global $wpdb;
$p_title = wp_unslash( sanitize_post_field( 'post_title', $title, 0, 'db' ) );
if ( !empty ( $title ) ) {
return (int) $wpdb->query("SELECT FROM $wpdb->posts WHERE post_title = $p_title");
}
return 0;
}
2 Answers
WordPress has a post_exists
function that returns the post ID or 0 otherwise.
So you can do
if ( 0 === post_exists( $title ) ) {
**YOUR_CODE_HERE**
}