Wordpress - How to get the custom post type from an archive page?

There are a several of ways to do this. Put:

var_dump($wp_query->query,get_queried_object()); die;

In your archive.php and you should see two of those ways.

$wp_query->query will have post_type component for custom post types. That will not be there for post post types. get_queried_object will return quite a bit of data for custom post types but null for post post type.

There are also some related template tags that might help. is_post_type_archive comes to mind.

Between those you should have the information you need to put together whatever logic you need. It is not clear from you question what the end result is supposed to be, so I can't really write much.

Since you specifically named archive.php that is what I tested in. You may need different code for some other template, especially with get_queried_object which returns very different information depending on the context.


Here is the function you want:

/**
 * Get the current archive post type name (e.g: post, page, product).
 *
 * @return String|Boolean  The archive post type name or false if not in an archive page.
 */
function get_archive_post_type() {
    return is_archive() ? get_queried_object()->name : false;
}

die(var_dump(get_taxonomy(get_queried_object()->taxonomy)->object_type));

I thinks that is the answer for your question.

Happy coding!!!