Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End working with wp_query in wordpress

  • This topic is empty.
Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #153983
    cybershot
    Participant

    I have a new query using wp_query. I want to get the category title. When I do a var dump of the variable used to hold the query, I get this

    `
    object(WP_Query)#231 (45) { ["query_vars"]=> array(60) { ["numberposts"]=> int(5) ["category_name"]=> string(5) "lunch"
    `

    I want the category name and thought I could do that by doing this

    $lunch->category_name;

    but I get an error that says “Undefined property”.

    I don’t understand what I am doing wrong.

    #154015
    Tomasz Lisiecki
    Participant

    Hi man,

    Where do you want to get the category name?

    #154016
    cybershot
    Participant

    I am trying to get it from within a custom query using WP query. I was trying to figure out why I couldn’t access the object and return the category name the way I was doing it.

    #154020
    Tomasz Lisiecki
    Participant

    Oh right. That makes more sense as you said you doing that within the query :)

    The old way is (your example solution):

    $lunch->query_vars['category_name'];
    

    But now we have more awesome way to do it :)

    $term = $lunch->get_queried_object();
    $term->category_name;
    

    OR (even more awesome way)

    $term_name = $lunch->get_queried_object()->category_name;
    

    However get_queried_object() returns the category object, if you are on category page (source)

    If you want to get the category name on the page you could do, I guess

    echo get_category(get_queried_object_id())->cat_name;
    

    Have a look at WP Codex for that functions if you need more explanations.

    Hopefully I understood what you need. You can paste your bits of code to explain it better.

    #154159
    cybershot
    Participant

    The more awesome way worked out for me… Thank you

    $term = $lunch->get_queried_object();
    $term->category_name;

Viewing 5 posts - 1 through 5 (of 5 total)
  • The forum ‘Back End’ is closed to new topics and replies.