首页 > 解决方案 > Woocommerce - 在类别页面的产品列表中添加到购物车按钮和数量

问题描述

我在特定类别页面上有一个自定义产品列表。

它看起来像这样:

产品列表类别页面缺少数量选择并在末尾添加到购物车按钮。

我一直在functions.php中使用以下内容,它运行良好。自上次更新 WooCommerce 以来,它不再有效。添加到购物车按钮和数量字段不再显示。

当我检查页面的 html 时,我没有收到任何错误,并且 qty 和按钮 html 所在的字段是空白的。

add_filter( 'woocommerce_loop_add_to_cart_link', 'quantity_inputs_for_woocommerce_loop_add_to_cart_link', 10, 2 );

function quantity_inputs_for_woocommerce_loop_add_to_cart_link( $html, $product ) {


    $term_id = get_queried_object()->term_id;
    $post_id = 'product_cat_'.$term_id;
    $wk_cat_value = get_term_meta($term_id, 'wh_meta_cat_template', true);

    // Only for this product category

    if ($wk_cat_value == 1 && is_product_category()) 

    {

        if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) 

        {
            $html = '<form action="' . esc_url( $product->add_to_cart_url() ) . '" class="cart" method="post" enctype="multipart/form-data">';
            $html .= woocommerce_quantity_input( array(), $product, false );
            $html .= '<button type="submit" class="button alt">' . esc_html( $product->add_to_cart_text() ) . '</button>';
            $html .= '</form>';


        }   
         return $html;
    }


}

此行是我在分类页面中添加的复选框,用于指定当前分类是否使用自定义模板: $wk_cat_value = get_term_meta($term_id, 'wh_meta_cat_template', true);

模板版本 Woocommerce 文件为 2.0.0。更新版本为 3.4.0。

任何建议都非常感谢。

标签: wordpressfunctionwoocommerce

解决方案


找到了解决方案:

function wk_add_to_cart() {

    $term_id = get_queried_object()->term_id;
    $post_id = 'product_cat_'.$term_id;
    // $wk_cat_value is a flag added to this specific category to decide whether or not the add to cart should be added
    $wk_cat_value = get_term_meta($term_id, 'wh_meta_cat_template', true);    

    global $product;

    if ($wk_cat_value == 1 && is_product_category()) {                

        if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() )  {

        echo '<form action="' . esc_url( $product->add_to_cart_url() ) . '" class="cart" method="post" enctype="multipart/form-data">';
        echo  woocommerce_quantity_input( array(), $product, false );
        echo  '<button type="submit" class="button alt">' . esc_html( $product->add_to_cart_text() ) . '</button>';
        echo  '</form>';

       }
    }
}

add_action('woocommerce_after_shop_loop_item','wk_add_to_cart');

希望有帮助。


推荐阅读