【问题标题】:wordpress get_the_category returns emptywordpress get_the_category 返回空
【发布时间】:2017-06-20 05:43:14
【问题描述】:

保存新评论后,我可以通过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。

你能帮忙吗? 非常感谢!

【问题讨论】:

    标签: wordpress


    【解决方案1】:

    我使用来自WooCommerce - get category for product page的这个sn-p通过get_the_terms解决了这个问题

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

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

    【讨论】:

    • 许多人混淆了自定义帖子类型和使用类别的术语。如果您将术语(您认为的类别)设置为“product_cat”或其他内容,则使用get_the_category() 找不到它,您正在执行get_the_terms( $post_id, 'category' ) 这就是您找不到它的原因。您必须先找到您的帖子类型的条款,然后尝试使用get_the_terms( $post_id, 'custom-term' )
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-11
    • 1970-01-01
    • 2011-05-30
    相关资源
    最近更新 更多