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.

Comments

Vishal Kakadiya — 2015-08-25
Hello Arash, Sorry but i think you forgot comma( , ) at the end of the 3rd line " 'name' => $slug ". If possible please put comma after that. Thank you.
ryan — 2015-09-24
thank you, really save my time
Arash Milani — 2015-11-12
@Vishal Kakadiya: Thank you for letting me know that. I did add that missing comma to that line.

Any thoughts? Please leave a reply

I'll use your email to show your picture using gravatar. I hate spam too.
Back to home

I'm Arash Milani, hacker & happiness ninja.
@narmand is our teams's lab to experiment awesome 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]arashmilani.com email address.