Search code examples
phpwordpressqtranslate

Determine the category identifier of the category page template in wordpress


This is something that has troubled me for the better part of the day. I created a new category.php template file for my girlfriend's cooking blog (you can see it here).

I wanted a specific layout for the category page - not the default one provided by the theme I use (Patchwork).

I googled around and eventually found that I could use the Wordpress PHP function <?php single_cat_title( $prefix, $display ); ?> as described in the Wordpress Codex. The point was then to use the Wordpress shortcode [catlist]. The shortcode can either take the category name or the category id.

I thought that would be it but unfortunately my girlfriend's blog is a bilingual one which means that single_cat_title doesn't always return the same value. It might return recipe in English and recette in French neither of which can be used to resolve the category in [catlist]. And if you think this is a corner case for bilingual blogs, it's not... It also applies to blogs that have categories with the same name (as to why you would have that, I don't know...)

All the other methods I could find were all specific to the_loop and not applicable in my case.

Anyway, I thought I would share the answer below for everyone's benefit. When I found it, it made my day!


Solution

  • The way to retrieve the current object identifier (be it a post, category, tag...) is to use the lower-level Wordpress objects and namely:

    $wp_query->get_queried_object_id()
    

    as described in Wordpress's class reference. The trick is to know the method name that gives you the property and Wordpress doesn't tell you that.

    The closest described method is get_queried_object() (see function reference).

    The final template for my page is as follows:

    <?php
    /**
     * The Template for displaying posts in the category view.
     *
     */
     get_header(); ?>
    
            <div id="primary" class="site-content">
                            <h1><?php single_cat_title("");?></h1>
                <div id="content" role="main">
    <?php echo do_shortcode('[catlist id='.$wp_query->get_queried_object_id().' orderby=date order=DESC excerpt=yes excerpt_size=25 thumbnail=yes numberposts=-1 template=del]'); ?>                
                </div><!-- #content -->
            </div><!-- #primary .site-content -->
    
    <?php get_sidebar(); ?>
    <?php get_footer(); ?>