微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 根据WooCommerce中的产品自定义字段和产品类别隐藏添加到购物车按钮

我想在woocommerce产品页面后端添加一个自定义复选框,隐藏前端的“添加到购物车”按钮.我不想完全删除购买该商品的能力(仍然希望能够使用直接添加到购物车网址将商品添加到购物车并购买)所以我不想使用add_filter(‘ woocommerce_is_purchasable’,’my_woocommerce_is_purchasable’,10,2);或类似的.

我目前取得的成就是:

添加自定义复选框

// display CheckBox
add_action('woocommerce_product_options_general_product_data', 'product_custom_fields_add');
function product_custom_fields_add(){
    global $post;

    echo '<div class="product_custom_field">';

    // Custom Product CheckBox Field
    woocommerce_wp_checkBox( array(
        'id'        => '_no_addcart_product',
        'desc'      => __('show or hide add to cart', 'woocommerce'),
        'label'     => __('Hide Add To Cart', 'woocommerce'),
        'desc_tip'  => 'true'
    ));

    echo '</div>';
}

// Save CheckBox
add_action('woocommerce_process_product_Meta', 'product_custom_fields_save');
function product_custom_fields_save($post_id){
    // Custom Product Text Field
    $no_addcart_product = isset( $_POST['_no_addcart_product'] ) ? 'yes' : 'no';
        update_post_Meta($post_id, '_no_addcart_product', esc_attr( $no_addcart_product ));
}

还有一个隐藏添加到购物车按钮,具体取决于类别片段.

function remove_product_description_add_cart_button(){
    global $product;      
    $category = 'hide';        
    if ( has_term( $category, 'product_cat', $product->id ) )
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
}

add_action('wp','remove_product_description_add_cart_button');

上述两种方法都可以自行完成.我失败的地方是尝试将它们组合起来只是为了删除添加到购物车按钮,如果复选框处于活动状态(我也不需要检查类别).我把下面的代码放在一起,希望它可以工作,但事实并非如此.

function remove_product_description_add_cart_button() {
    if ( is_product() && get_post_meta( $post->ID, '_no_addcart_product', true ) == 'yes' ) {
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
}

add_action('wp','remove_product_description_add_cart_button');

非常感谢您提供正确方向的任何帮助.

解决方法:

您可以通过以下方式将两个条件与关系OR参数组合在一起:

add_action( 'woocommerce_single_product_summary', 'remove_product_add_to_cart_button', 4 );
function remove_product_add_to_cart_button(){
    global $product;

    $term_slug = 'hide'; // Product category term slug

    if ( has_term( $term_slug, 'product_cat', $product->get_id() ) || $product->get_Meta('_no_addcart_product') === 'yes' )
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
}

代码位于活动子主题(或活动主题)的function.PHP文件中.它应该工作.

Note: Since Woocommerce 3 the WC_Product properties can’t be accessed directly so you need to use the available methods with the WC_Product Object $product.

  • For the product ID you will use get_id() method like: $product->get_id()
  • For product custom Meta data you can also use get_Meta() method

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐