【问题标题】:Adding Extra Add to cart button below product summary in Woocommerce在 Woocommerce 中的产品摘要下方添加额外的添加到购物车按钮
【发布时间】:2018-04-16 07:00:25
【问题描述】:

在 WooCommerce 中,我正在尝试在产品摘要下方添加一个额外的添加到购物车按钮。我成功地在此代码之后添加了一个适用于单个产品的额外按钮:

add_action( 'woocommerce_single_product_summary', 'custom_button_after_product_summary', 30 );

function custom_button_after_product_summary() {
  global $product;
  echo "<a href='".$product->add_to_cart_url()."'>add to cart</a>";
}

但如果产品是变体,它就不起作用。

请建议怎么做?

【问题讨论】:

    标签: php wordpress woocommerce product hook-woocommerce


    【解决方案1】:

    我重新审视了您的代码,并为可变产品添加了第二个挂钩函数:

    // For Simple products
    add_action( 'woocommerce_single_product_summary', 'second_button_after_product_summary', 30 );
    function second_button_after_product_summary() {
        global $product;
    
        if( ! $product->is_type( 'variable' ) )
            echo '<button type="submit" name="add-to-cart" value="'. esc_attr( $product->get_id() ).'" class="single_add_to_cart_button button alt">'. esc_html( $product->single_add_to_cart_text() ).'</button>';
    }
    
    // For Variable products
    add_action( 'woocommerce_single_variation', 'second_button_single_variation', 30 );
    function second_button_single_variation() {
        global $product;
    
        echo '<br>
            <button type="submit" class="single_add_to_cart_button button alt">'. esc_html( $product->single_add_to_cart_text() ).'</button>';
    }
    

    代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件中。

    您将在可变产品上获得此信息:

    【讨论】:

    • 我遵循了您的代码,尽管它在单击时输出了第二个按钮,但并未将产品添加到购物车中
    • 按钮无法工作,因为它缺少动作属性。只需添加返回产品永久链接的操作。 action="'. esc_url( apply_filters( 'woocommerce_add_to_cart_form_action', $product-&gt;get_permalink() ) ); .' "
    【解决方案2】:

    @LoicTheAztec 提供的答案是正确的,但它缺少按钮单击事件的操作属性。这是带有 action 属性的更正代码。

    // For Simple products
    add_action( 'woocommerce_single_product_summary', 'second_button_after_product_summary', 30 );
    function second_button_after_product_summary() {
        global $product;
    
        if( ! $product->is_type( 'variable' ) )
            echo '<button type="submit" name="add-to-cart" value="'. esc_attr( $product->get_id() ).'" action="'.esc_url( apply_filters( 'woocommerce_add_to_cart_form_action', $product->get_permalink() ) ).'" class="single_add_to_cart_button button alt">'. esc_html( $product->single_add_to_cart_text() ).'</button>';
    }
    

    如果您使用的是外部产品或变体项目,请适当添加操作属性。请参考“plugins/woocommerce/templates/single-product/add-to-cart”

    【讨论】:

      猜你喜欢
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-04
      • 2014-11-21
      相关资源
      最近更新 更多