Whenever you need to get the post type for a given post, there are a couple of ways to do this:
- If you’re in the dashboard, then you can use `get_current_screen()` and then access the `id` property of the object that’s returned. You can read more about this in the Codex.
- If you’re on the front-end (or even in the dashboard, really), you can use `get_post_type`. This is also covered in the Codex.
The Post Type of the Current Post
In terms of why you’d want to do this, your mileage may vary. I know for 99% of the time, using the server-side is faster, fits most use cases, and generally will achieve whatever it is that you need. In short, it’s “more correct.”
But there are times where we have to get creative in our solutions.
I know that as “ideal” as the server-side is, sometimes projects call for less-than-stellar solutions. Not everything works as it should all the time. This results in us needing to get creative with how we do things.
Anyway, the following code assumes that the
body element has the
body_class() API function placed in the template such that the
class attribute contains the post type.
Assuming that’s true, here’s how to get the post type of the current post from the class name of the
First, the code iterates through the class names on the
body element of the current page. It examines each of the first 10 characters of the substring of the current class name as the post type of the current post is specified as
If the substring matches the expected post type class name, then it reads the post type as the last bit of the class name that comes after
post-type-. From there, it stores it into the
postType variable and returns from the iterator.
Note that the variables are defined outside of the
dom.ready function so that the variables can be used throughout the rest of the code. If the class name (or post type) is never found, then the variable will be set to null so that you can evaluate it later in the code base.
When Would I Ever Use This?
This is just a code snippet. For reuse, it may need to be moved into its own function or it’s own file and then called or included in whatever way works best with your code.
If, however, you find yourself working on something that’s an edge case, on the fringe, or for whatever reasons you may have, the above code is one way to do it.