wordpress get_the_category returns empty

2019-07-27 08:45发布

After a new comment is saved, I’m able to redirect via functions.php

add_filter('comment_post', 'myredirect');

I want to redirect to the product category listing, say: http://example.org/baktec27/?product_cat=1a

So I need the category for the current post. Couldn’t access $post from functions.php so got post_id from $GLOBALS

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

// according to https://developer.wordpress.org/reference/functions/get_the_category/

// also tried 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");
}

I get an empty $categories.

Can you help? Thanks a lot!

标签: wordpress
1条回答
我命由我不由天
2楼-- · 2019-07-27 09:12

I got it solved via get_the_terms using this snippet from WooCommerce - get category for product page

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

Foundit when i looked for product instead of post. :-)

查看更多
登录 后发表回答