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 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 function get_the_ID()
:
while ( $cat_query->have_posts() ) : $cat_query->the_post();
array_post( $matching_category_ids, get_the_ID() );
endwhile;