Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I've got some code that I want to turn into a function. It works great until I wrap it in said function:

    $args = array(
        'posts_per_page'    =>  -1,
        'post_type'         =>  'asset',
        'category_name'     =>  $cat
    );
    $cat_query = new WP_Query( $args );
    $matching_category_ids = array();       
    while ( $cat_query->have_posts() ) : $cat_query->the_post();
        array_push($matching_category_ids, $post->ID);
    endwhile;

The function looks something like this:

function grab_ids_in_category($cat) {
    //stuff from above here
    return $matching_category_ids;
}

What am I doing wrong?

share|improve this question

2 Answers 2

up vote 3 down vote accepted

Simple, you're addressing $post out of context.

When you're running a standard WordPress loop, WP will load a global $post variable with the results of the current query. This includes the ID, title, content, post meta, etc. The loop functions will reference this global variable to actually give you data.

Take the regular function get_the_ID() for example:

function get_the_ID() {
    global $post;
    return $post->ID;
}

Your code will work fine outside of a function because, somewhere in the code above it, you're probably globalizing the $post variable. So your direct reference to $post->ID works.

But when you wrap this code inside a function, you aren't referencing $post as a global, so $post->ID won't return anything because the local $post is undefined.

Instead of referencing $post->ID directly, use the regular loop function get_the_ID():

while ( $cat_query->have_posts() ) : $cat_query->the_post();
    array_post( $matching_category_ids, get_the_ID() );
endwhile;
share|improve this answer
    
Amazing. Thank you for such a thorough answer. –  perpetualstudent Jun 25 '12 at 18:29

You have to add the global variable $post into the function like this:

function grab_ids_in_category($cat) {

    global $post;

    $args = array(
        'posts_per_page'    =>  -1,
        'post_type'         =>  'asset',
        'category_name'     =>  $cat
    );

    $cat_query = new WP_Query( $args );

    $matching_category_ids = array();

    while ( $cat_query->have_posts() ) : $cat_query->the_post();
        array_push($matching_category_ids, $post->ID);
    endwhile;

    return $matching_category_ids;

}

// echo the Query and pass a category name 
echo grab_ids_in_category('category_name');
share|improve this answer
    
Thank you! This is great. –  perpetualstudent Jun 25 '12 at 18:30

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.