WP_Query in functions.php

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:

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

What am I doing wrong?

Related posts

Leave a Reply

2 comments

  1. 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;
    
  2. 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');