WordPress giving great features in get_posts function with arguments that function also having great customization. get_posts function also give us great result of posts with our complex requirements, so through that function we will get post by post’s url-slug-key. Check out following function I have created to used it easily and post_type is required I have used it for my custom post type “services” you must have to pass it otherwise get_posts don’t return null.
function get_posts_by_urlslug($the_slug){ $args = array( 'name' => $the_slug, 'post_type' => 'services', 'post_status' => 'publish', 'posts_per_page' => 1 ); return get_posts( $args ); } echo '<pre>';print_r(get_posts_by_urlslug('laravel-generate-online-password'));echo '</pre>';
Here is example of the called function
Array ( [0] => WP_Post Object ( [ID] => 9364 [post_author] => [post_date] => 2018-02-25 20:25:19 [post_date_gmt] => 2018-02-25 15:25:19 [post_content] => [post_title] => Laravel generate online password [post_excerpt] => [post_status] => publish [comment_status] => open [ping_status] => closed [post_password] => [post_name] => laravel-generate-online-password [to_ping] => [pinged] => [post_modified] => 2018-02-28 00:32:28 [post_modified_gmt] => 2018-02-27 19:32:28 [post_content_filtered] => [post_parent] => 0 [guid] => http://sdtuts.com/?post_type=services&p=9364 [menu_order] => 0 [post_type] => services [post_mime_type] => [comment_count] => 0 [filter] => raw ) )