Search code examples
wordpressslug

Wordpress - How to get custom post type by slug?


I'm in a situation where I need to get a WP post (custom post type) and the only information I have is its slug. I don't know what custom post type it is, just that it's a cpt.

Is this possible to do, and if so, how?


Solution

  • global $wpdb;
    $the_slug = 'post-slug-here'; // <-- edit it
    $myrows = $wpdb->get_results( "SELECT post_name, post_type, ID FROM wp_posts WHERE post_name = '". $the_slug ."'" );
    foreach ( $myrows as $myrow ) 
    {
        echo 'Post Type: ' . $myrow->post_type . ' Post ID: ' . $myrow->ID;
    }