문제

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