(修改后的答案)
因此,我假设该类别中实际上有帖子(ID:31), 并基于wp_get_post_terms() reference:
$post_id
(int)(可选)Post ID。Does not default to the ID of the global $post. 默认值0。
很可能您没有将正确的post ID传递给wp_get_post_terms() 功能:
wp_get_post_terms( $post->ID, \'category\', array(...) );
在代码中
$post 然而,它并没有像问题中那样在代码中的任何地方定义。
因此,如果您试图在WordPress循环中获取当前帖子的ID,其中帖子数据存储在全局$post 变量,则应首先使用global $post; 像这样:
global $post;
// here and after this line, you may now use $post->ID
if( $query->have_posts() ) :
...
endif;
或者你也可以使用
get_the_ID() 无需这样做
global $post;, 特别是如果您只想获得帖子ID:
wp_get_post_terms( get_the_ID(), \'category\', array(...) ); // here I don\'t use $post->ID
可能值得一提的是,在标准模板中
page.php, 全球
$post 变量已经是“全局ed”,因此您可以访问
$post 模板中的任意位置。(好吧,不完全是“任何地方”;然而,我不打算在这个答案中更深入地探讨这个问题……)
附加说明这可能只是一个输入错误,但在问题中的代码中,出现了一个语法错误:
foreach ( $brands as $brand ) {
echo $brand->name;
}; // <- remove that ;
你忘了关门
endif;..