Quick WP Tip: get_queried_object()

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!

Tags:


Yoast.com runs on the Genesis Framework

Genesis theme frameworkThe Genesis Framework empowers you to quickly and easily build incredible websites with WordPress. Whether you're a novice or advanced developer, Genesis provides you with the secure and search-engine-optimized foundation that takes WordPress to places you never thought it could go.

Read our Genesis review or get Genesis now!

7 Responses

  1. Andrew NacinBy Andrew Nacin on 13 October, 2010

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

  2. JaredBy 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 :)

  3. Dave WrightBy Dave Wright on 14 October, 2010

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

  4. subraBy 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.

  5. johnBy john on 22 October, 2010

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

  6. NetBloggerBy 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?

Trackbacks