有条件地显示Woocommerce结帐字段

时间:2017-12-08 21:06:21

标签: php wordpress woocommerce field checkout

在Wordpress网站上,我目前正在尝试设置Woocommerce和Learnpress插件。我使用Woocommerce Checkout Add-ons商业插件,允许创建一些额外的结帐字段。

我只想在结帐购物车中出现某些Learnpress课程时有条件地显示一些结帐字段。

结帐插件中的代码如下:

<?php if ( $add_on_fields ) : ?>

<div id="wc_checkout_add_ons">
<?php
    foreach ( $add_on_fields as $key => $field ) :
        woocommerce_form_field( $key, $field, WC()->checkout()->get_value( 
        $key ) );
    endforeach;
?>
</div>

<?php endif; ?>

所以开始走这条路:

<div id="wc_checkout_add_ons">
<?php 
    $course_category = get_the_terms( $post->ID, 'course_category' );
    echo $course_category; 
    if ($course_category == 'weekend-intensives') { 
        foreach ( $add_on_fields as $key => $field ) : 
            woocommerce_form_field( $key, $field, WC()->checkout()->get_value( $key ) ); 
        endforeach; 
    } else { 
        echo ('Proceed with checkout'); 
    } 
?> 
</div>

现在我甚至没有获得$course_category的初始回音所以我知道我已经错了......

我需要弄清楚在结帐/购物车中获取课程学习课程类别的代码。
我知道除此之外还有更多内容,我可能会离开,但我愿意在一些帮助下完成它。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

您可以将has_term()特定的WordPress条件函数用于自定义分类和自定义分类,作为“产品类别”或您的案例“课程类别”,您可以轻松使用。

1)你需要检查购物车项目,看看是否有一个购物车项目仍然是“周末密集型”课程类别,这必须在代码的开头完成。这样您就可以改变现有条件if ( $add_on_fields ) : ...

2)您需要确保课程类别分类标准适用于WooCommerce 产品自定义帖子类型。如果没有,您将无法检查任何课程类别购物车项目。

所以正确的方法是:

<?php
    ## ---- Custom code start here ---- ##
    $is_in_cart = false;

    // Checking cart items for specific "Course category"
    foreach( WC->cart->get_cart() as $cart_item ){
        // Here your Course category
        if( has_term( 'weekend-intensives', 'course_category', $cart_item['product_id'] ){
            $is_in_cart = true; // Found
            break; // Stop the loop
        }
    }
    // adding our condition in existing code if statement
    if ( $add_on_fields && $is_in_cart ) : 

    ## ---- Custom code Ends here ---- ##

    // if ( $add_on_fields ) :
?>

<div id="wc_checkout_add_ons">
<?php
    foreach ( $add_on_fields as $key => $field ) :
        woocommerce_form_field( $key, $field, WC()->checkout()->get_value( $key ) );
    endforeach;
?>
</div>

<?php endif; ?>

这是未经测试的,但应该有效(如果课程类别适用于WC产品)

更新

检查产品ID是否适用于“周末密集型”课程类别:

  • 代码进入活动子主题(或主题)的function.php文件。
  • 在其中设置正确的产品ID以进行检查和保存。
  • 进入档案页面或产品页面查看结果(保存一次后)。

代码:

// Checking for "weekend-intensives" course category in shop and product pages
add_action( 'woocommerce_before_main_content', function(){
    // Only for admin user role
    if( ! current_user_can('edit_products')) return;

    // ==> BELOW set your product ID to check
    $product_id = 43;

    // Output the raw cart object data
    if( has_term( 'weekend-intensives', 'course_category', $product_id ){
        echo '<pre>YES! This product works with "weekend-intensives" course category</pre>';
    } else {
        echo '<pre>This product DOES NOT WORK with "weekend-intensives" course category</pre>';
    }
}, 987 );