wordpress get_the_category 返回空 [英] wordpress get_the_category returns empty
问题描述
保存新评论后,我可以通过functions.php重定向
After a new comment is saved, I’m able to redirect via functions.php
add_filter('comment_post', 'myredirect');
我想重定向到产品类别列表,例如:http://example.org/baktec27/?product_cat=1a
I want to redirect to the product category listing, say: http://example.org/baktec27/?product_cat=1a
所以我需要当前帖子的类别.无法从functions.php 访问$post 所以从$GLOBALS 获取post_id
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
//根据 https://developer.wordpress.org/reference/functions/get_the_category/
//也试过 wp_get_post_categories( $post_id )
// 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");
}
我得到一个空的 $categories.
I get an empty $categories.
你能帮忙吗?非常感谢!
Can you help? Thanks a lot!
推荐答案
$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. :-)
这篇关于wordpress get_the_category 返回空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!