Get category ID in “archive-product.php”

Normally this should work with get_queried_object_id().

Anyway, as I don’t know what Woo exactly does to the query, this can be as well wrong, as the API function references to the object that is currently queried. And this is the object from the last query. So you might also do the following:

Disclaimer: The below written function is not tested and you should var_dump() your way through until it works (and then edit this question with your result and delete this lines here).

<?php 
defined( 'ABSPATH' ) OR exit;
/** Plugin Name: Cat ID helper for WooCommerce */

add_action( 'pre_get_posts', 'wpse_98288_get_object_id', 0 );
function wpse_98288_get_object_id( $query = null )
{
    static $id = 0;

    if ( 'pre_get_posts' === current_filter() )
        remove_filter( current_filter(), __FUNCTION__ );

    $query->is_main_query()
        AND $id = $query->get( 'cat_id' );

    if ( null !== $query )
        return $query;

    return $id;
}

So this is a multi-purpose function, that must be used as plugin (even better: as mu-plugin). It adds itself to the loop/wp_query building process and tries to fetch the ID from the main loop. Then you can call it again by its function name in your template and it should output the ID.

Point is that you’ve to work with var_dump( $wp_query ) to determine what exactly is set and grab what you need as I don’t know the value names right now straight off my head.

Leave a Comment