How to get a WordPress post by slug 1391/11/10

I was developing a  WordPress plugin using custom post types then I needed to retrieve a post by its slug. Here I'm trying to get a custom post type called "product". you can replace the post type according to your needs. generic types are "post" and "page".

function get_post_by_slug($slug){
    $posts = get_posts(array(
            'name' => $slug
            'posts_per_page' => 1,
            'post_type' => 'product',
            'post_status' => 'publish'
    if(! $posts ) {
        throw new Exception("NoSuchPostBySpecifiedID");

    return $post[0];

Check the WordPress reference on the return value of the function that's a wp post object. Also note that I'm not a fan using NULL as return value for functions so this function will throw an exception in case of failure.

Back to home

I'm Arash Milani, hacker, avid reader, happiness ninja.
@narmand is our teams's lab to expriment awsome things in it.

I write and talk about hacking, developing web apps, teamwork and designing for better user experience.

You can always contact me via me[at] email address.