Question

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?

Était-ce utile?

La 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;
}

Autres conseils

I know this is a late reaction, but I stumbled upon this. Be careful with such queries because it can be easely injected with SQL vulnerabilities whan you grab the slug from your url.

If you know for sure all the custom post types that were defined in your WordPress theme or plugins, it's probably better to use a dedicated function like get_page_by_path(). It will prevent users from trying to inject SQL in a query.

For example :
get_page_by_path( 'slug_of_the_post', OBJECT, [ 'list', 'of', 'possible', 'types' ] );

See code reference of the function.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top