0

I've been struggling with a quite specific point. I registered some custom post types and specified the rewrite slug for each one of them.

'rewrite'           => array( 'slug' => 'my-slug' ),

But later when i'm trying to use the "rewrite slug" and to find which post_type is requested I cannot use the get_post_type() function : the post_type isn't recognized from the rewrite slug.

get_post_type( 'my-slug' )

returns

bool(false)

Does anyone have an elegant solution to find a post_type from its rewrite slug ?

  • 2
    The slug is the key you registered the post type under (the first argument of register_post_type), not the rewrite slug. – Milo Jan 10 '18 at 23:30
  • Can you be a bit more precise? Do you want to check the rewrite slug of the current page you're at to find out which post type it might belong to? – swissspidy Jan 17 '18 at 13:28
  • Yes : my question is definitely to find out which post_type a given rewrite slug belongs to ! (in a context where the targeted post_type is not available using the get_queried_object function). – MrUzu Jan 19 '18 at 12:08
2

There are two ways I've used for doing this...each with issues:

This one this only works if you've set the rewrite slug for your CPT. if you don't set one it could lead to an error:

$post_type = get_queried_object();
echo $post_type->rewrite['slug'];

This one will not work on archive pages, because the page type will be "page":

$post_type = get_post_type();
if ( $post_type )
{
    $post_type_data = get_post_type_object( $post_type );
    $post_type_slug = $post_type_data->rewrite['slug'];
    echo $post_type_slug;
}
  • Thanks for that answer, but has you noticed you sometimes find yourself in a context where the queried object is not what your working on. For instance i'm working on a standard page that displays other post types : www.mydomain.com/my-page/my-custom-post-type-posts – MrUzu Jan 11 '18 at 9:21
  • So use option 1 – rudtek Jan 11 '18 at 16:51
  • Option 1 does not answer my problem,which is to find a post_type from its "rewrite slug". In option 1 you get the from get_queried_object which is not relevant in my case – MrUzu Aug 29 '18 at 12:14
0

I've finally had time to investigate and found a solution (this post helped me : Get list of all registered post types slugs).

From what I know the only to get a Post Type using its rewrite slug is to loop over the registerd post types and compare the rewrite slug with the one requested.

$types = get_post_types( ['public'   => true,'_builtin' => false], 'objects' );
foreach ( $types as $type ) {
    if ( isset( $type->rewrite['slug'] ) && 'my-rewrite-slug' == $type->rewrite['slug'] ) {
        $post_type_obj = $type;
        continue;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.