Using IDs or query_vars instead of slug names in get_post_types

Here’s one that had my head scratching for a while.

We are currently developing a much-sought-after update for Carousel Anything, and it involves enumerating post types, taxonomies and terms. On a routine testing en route to being a candidate build, our testing team found out it wasn’t working with the custom post types by Meet The Team.

Several comparative var dumps later, I learned it wasn’t returning the correct post type variable!

Then I was reminded I implemented a feature previously in Meet The Team where I could change the slug name to something far more frendlier. It was friendly for readers in SEO, but not for the devs.

Or so I thought.

This meant slugs can’t be used for internal queries because it could be modified midway and wasn’t reliable, until I scoured a var dump of get_post_types() and found what I needed.

The query_vars key.

At last, this was the id that identified each post type reliably. And most slugs take up its name! No wonder why some post types worked and some did not!

That’s one piece of code definitely going to the snippets.

Here is what was wrong before.

$posttypes['slug'][] = $post_type->rewrite['slug'];
$posttypes['name'][ $post_type->rewrite['slug'] ] = $post_type->labels->name;

And here’s the code that set things right.

$posttypes['slug'][] = $post_type->query_var;
$posttypes['name'][ $post_type->query_var ] = $post_type->labels->name;

Leave a Reply

Your email address will not be published. Required fields are marked *