很简单,您正在寻址$post 脱离上下文
当您运行标准WordPress循环时,WP将加载一个全局$post 具有当前查询结果的变量。这包括ID、title、content、post meta等。循环函数将引用此全局变量以实际提供数据。
取常规函数get_the_ID() 例如:
function get_the_ID() {
global $post;
return $post->ID;
}
您的代码在函数之外可以正常工作,因为在它上面的代码中,您可能
global正在调整
$post 变量所以你直接参考
$post->ID 作品
但是,当您将此代码包装到函数中时,您不是在引用$post 作为一个全球性的$post->ID 不会返回任何内容,因为本地$post 未定义。
而不是引用$post->ID 直接使用正则循环函数get_the_ID():
while ( $cat_query->have_posts() ) : $cat_query->the_post();
array_post( $matching_category_ids, get_the_ID() );
endwhile;