Check if post exists by slug in WordPress

if ( ! function_exists( 'wpcodebook_post_exists_by_slug' ) ) {
    /**
     * Checks if post exists by slug.
     *
     * @see    https://wpcodebook.com/snippets/check-if-post-exists-by-slug-in-wordpress/
     * @return mixed boolean false if no posts exist; post ID otherwise.
     */
    function wpcodebook_post_exists_by_slug( $post_slug ) {
        $loop_posts = new WP_Query( array( 'post_type' => 'post', 'post_status' => 'any', 'name' => $post_slug, 'posts_per_page' => 1, 'fields' => 'ids' ) );
        return ( $loop_posts->have_posts() ? $loop_posts->posts[0] : false );
    }
}

Usage example:

wpcodebook_post_exists_by_slug( 'hello-world' );

Leave a Comment