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.
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.
Comments
Any thoughts? Please leave a reply