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?
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:Your code will work fine outside of a function because, somewhere in the code above it, you’re probably
global
izing 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 functionget_the_ID()
:You have to add the global variable $post into the function like this: