Quick WP Tip: get_queried_object()

October 13th, 2010 – 7 Comments

Getting the queried object in WordPress can be done in two ways: the hard way, and the easy way. Unfortunately for me, I only found out about the easy way a couple of days ago… The class wp_query has a function get_queried_object() that can be quite useful. Let me show you the old code I used:

if ( is_tax() || is_tag() || is_category() ) {
	// Because WP doesn't set taxonomy and term on 
	// category and tag pages we need to grab them here.
	if ( is_tag() ) {
		$taxonomy 	= 'post_tag';
		$term 		= $wp_query->query_vars['tag'];
	} else if ( is_category() ) {
		$taxonomy 	= 'category';
		$term		= $wp_query->query_vars['category_name'];
	} else {
		$taxonomy 	= $wp_query->query_vars['taxonomy'];
		$term 		= $wp_query->query_vars['term'];

	$term = get_term_by( 'slug', $term, $taxonomy );

See how that is a bit ugly? That shouldn’t be necessary right? (Let’s not talk about the fact that is_tax() returns false when in a category or tag archive, even though that’s weird at least.) Let’s see how it can be done with get_queried_object:

if ( is_tax() || is_tag() || is_category() ) {
	$term = $wp_query->get_queried_object();

That’s like 20 times more efficient right? Looking through my code I have used this call in the past, but somehow forgot about it. Hence this reminder to myself, and all of you, that it’s there and that it can do some wonderful things for you!

7 Responses to Quick WP Tip: get_queried_object()

  1. NetBlogger
    By NetBlogger on 30 October, 2010

    Sounds like a great plugin,is this still in Beta?
    At the moment I am using All in One SEO and XML sitemaps plugin.
    Is it recommended to delete those plugins and start using your new plugin?

  2. john
    By john on 22 October, 2010

    sorry for the stupid question, but for what is this good? the site will load faster?

  3. subra
    By subra on 22 October, 2010

    i’am setting up my wordpress blog completely based on your tips. thank you for your awesome tips and assists.

  4. Dave Wright
    By Dave Wright on 14 October, 2010

    useful tip, have been doing a bit with refining queries recently and can see this coming in handy

  5. Jared
    By Jared on 13 October, 2010

    I always forget about get_queried_object too, and have used it many times.
    Same goes for $wp_query->get_query_object_id() @nacin

    Always good to be reminded of them :)

  6. Andrew Nacin
    By Andrew Nacin on 13 October, 2010

    And there’s $wp_query->get_queried_object_id(), as well.

Check out our must read articles about Analytics