【问题标题】:WooCommerce - Conditional has_term doesn't work anymore after updatingWooCommerce - 更新后有条件的 has_term 不再起作用
【发布时间】:2016-08-25 02:25:13
【问题描述】:

所以我使用example 中的代码片段的条件,this thread code 成功:

但是更新我的 WordPress 核心和 WooCommerce 插件后它不再工作了。

if ( is_product() && has_term( 'sample-category', 'product_cat' ) ){

    add_action( 'woocommerce_after_add_to_cart_button', 'add_custom_button', 10, 0 );
    function add_custom_button() {
        global $products;

        $product_link = get_permalink( $products->id );
        $sample_link = substr($product_link, 0, -1) . '-swatch-card/';
        echo '<a class="button alt btn-sample" href="' . esc_url( $sample_link ) .'">' . __( "Order a Sample", "my_theme_slug" )  . '</a>';

    }

}

子插件在 function.php 文件中仍然有正确的代码。

请问我该如何解决这个问题?

谢谢

【问题讨论】:

    标签: php wordpress woocommerce categories product


    【解决方案1】:

    尝试这种方式可能是,使用 $post 全局对象并将条件嵌入到你的函数中:

    add_action( 'woocommerce_after_add_to_cart_button', 'add_custom_button', 10, 0 );
    function add_custom_button() {
        global $post;
        if ( has_term( 'collection', 'product_cat', $post->ID ) ) {
            $product_link = get_permalink( $post->ID );
            $sample_link = substr($product_link, 0, -1) . '-swatch-card/';
            echo '<a class="button alt btn-sample" href="' . esc_url( $sample_link ) .'">' . __( "Order a Sample", "my_theme_slug" )  . '</a>';
        }
    };
    

    条件 has_term() 有时需要它的第三个参数才能工作......在 function.php 中它找不到当前帖子所以在这种情况下最好将它嵌入到 $post 或 $product 全局对象之后的函数中。

    【讨论】:

    • 只是为了添加注释,全局 $product 在 WooCommerce 3.4.2 中不起作用。 $post 和 $post->ID 确实
    猜你喜欢
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    • 2017-02-16
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    相关资源
    最近更新 更多