wordpress get_the_category returns empty



保存新评论后,我可以通过函数重定向.php

add_filter('comment_post', 'myredirect');

我想重定向到产品类别列表,比如:http://example.org/baktec27/?product_cat=1a

所以我需要当前帖子的类别。 无法从函数访问$post.php所以从$GLOBALS post_id

$post_id = $GLOBALS[_POST][comment_post_ID];    // ok

根据 https://developer.wordpress.org/reference/functions/get_the_category/

还尝试过wp_get_post_categories( $post_id (

$categories = get_the_category($post_id);
if ( ! empty( $categories ) ) {
    file_put_contents('testfile2.txt', esc_html( $categories[0]->name));
} else {
    file_put_contents('testfile2.txt', "NOTHING HERE");
}

我得到一个空$categories。

你能帮忙吗?多谢!

我通过使用 WooCommerce 中的此代码段通过get_the_terms解决了它 - 获取产品页面的类别

$terms = get_the_terms( $post_id, 'product_cat' );
foreach ($terms as $term) {
    $product_cat_id = $term->slug;
    break;
}

当我寻找产品而不是帖子时发现它。

最新更新