wordpress get_the_category返回空

时间:2017-02-02 23:34:55

标签: wordpress

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

add_filter('comment_post', 'myredirect');

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

所以我需要当前帖子的类别。无法从functions.php访问$ post,所以从$ 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。

你能帮忙吗? 非常感谢!

1 个答案:

答案 0 :(得分:1)

我使用WooCommerce - get category for product page

中的此片段通过get_the_terms解决了这个问题
  // from:https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/remove()/remove().md
    (function (arr) {
        arr.forEach(function (item) {
            item.remove = item.remove || function () {
                this.parentNode.removeChild(this);
            };
        });
    })([Element.prototype, CharacterData.prototype, DocumentType.prototype]);

Foundit当我寻找产品而不是帖子。 : - )

相关问题