Check if post exists by slug in WordPress

Usage example:
wpcb_post_exists_by_slug( 'hello-world' );

if ( ! function_exists( 'wpcb_post_exists_by_slug' ) ) {
    /**
     * Check 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 wpcb_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 );
    }
}

You can add this snippet to your (child) theme's functions.php file.

No comments yet.

Leave a Reply