1

I am trying to find out the post type from a category id.

Suppose that, when i am opening a category page

localhost/project/foobaar/category/pen

I want to know the post type to which category - pen is attached to. I have two custom post type named "book" and "copy" If category pen is associated with book, then it should return the post type as "book" Similarly if category is pencil, then it should return "copy" as i have used pencil category in "copy" post.

I was trying to do something like this as (i have the category id stored in variable but assume category id of pen is 12)

$args = array (
    posts_per_page => 1,
    category => '12' // category id of pen
    );
$posts = WP_Query( $args );

And from $posts I could get one post from which I could knew, but $args is using default post_type as 'posts' and my posts can be anything.

Thanks

  • 1
    I don't understand what you want, but one thing I can tell you, you should not run a custom query on your category page if it is suppose to be the main query. This breaks your whole category page functionality – Pieter Goosen Apr 17 '15 at 12:52
2

You can just grab the first post from the main query and see which post type it is:

if ( have_posts() ) {
    $post_type = $wp_query->posts[0]->post_type;
}

If you run this code directly in a main template file you should be fine, but if it's in a function you will need to call global $wp_query; first.

  • 1
    I am not sure, but can't you have the same taxonomy used for two different post types? so at best the answer should be qualified to be only valid when you have the taxonomy used only by one post type – Mark Kaplun Apr 17 '15 at 17:56

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.