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?

有帮助吗?

解决方案

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

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top