WordPress.org

Ready to get started?Download WordPress

Forums

Looping through post_category and getting category names (5 posts)

  1. daverage
    Member
    Posted 1 year ago #

    Hi.

    I am working on a plugin that is using wp_query. The basic loop is

    $the_query = new WP_Query($args);
            foreach ($the_query->posts as $cp) {
    }

    I can get almost everything I need, but I am really struggling to return category names for the current post! I can get an array of the id's
    $cp->post_category

    But I can find nothing that makes sense to me or that works to pull the category names from that - and ideally display them as hyperlinks.

    Can anyone help - I am sure this is really easy!!!

  2. alchymyth
    The Sweeper & Moderator
    Posted 1 year ago #

    what is the result if you temporarily add this line for testing:

    var_dump( $cp->post_category );

    if it results in a array of category ids, loop through it with a 'foreach' and use get_category() for each id and get_category_link()

    http://codex.wordpress.org/Function_Reference/get_category
    http://codex.wordpress.org/Function_Reference/get_category_link

  3. daverage
    Member
    Posted 1 year ago #

    Thanks.

    I get this

    array(1) { [12]=> string(2) "12" }

    Sorry, I am very new to PHP!!!

  4. alchymyth
    The Sweeper & Moderator
    Posted 1 year ago #

    try (untested):

    if( $cp->post_category  ) foreach( $cp->post_category as $cat_id ) {
    echo '<a href="' . get_category_link($cat_id) . '">' . get_category( $cat_id )->cat_name . '</a>';
    }
  5. daverage
    Member
    Posted 1 year ago #

    Thank you!!! That worked first time!!!

Topic Closed

This topic has been closed to new replies.

About this Topic