Change “add to cart” text if a user has bought specific products in WooCommerce

懵懂的女人 提交于 2021-02-05 12:13:37

问题


I wanted to know if there is a way to replace the woo-commerce "add to cart" button with custom text and url for a specific product if the user has bought that specific product.

and I want it happens everywhere (on shop page,product page , ...)


回答1:


Try the following that will change the product "add to cart" text if that product has already been bought by the customer on single product pages and archive pages

add_filter( 'woocommerce_product_add_to_cart_text', 'custom_add_to_cart_text', 900, 2 ); // Archive product pages
add_filter( 'woocommerce_product_single_add_to_cart_text', 'custom_add_to_cart_text', 900, 2 ); // Single product pages
function custom_add_to_cart_text( $button_text, $product ) {
    $current_user = wp_get_current_user();

    if( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product->get_id() ) ) {
        $button_text = __("Custom text", "woocommerce");
    }
    return $button_text;
}

Code goes in functions.php file of your active child theme (or active theme). It should work.


Now you can also restrict that to specific product ids like:

add_filter( 'woocommerce_product_add_to_cart_text', 'custom_add_to_cart_text', 900, 2 ); // Archive product pages
add_filter( 'woocommerce_product_single_add_to_cart_text', 'custom_add_to_cart_text', 900, 2 ); // Single product pages
function custom_loop_add_to_cart_button( $button_text, $product ) {
    $current_user = wp_get_current_user();

    // HERE define your specific product IDs in this array
    $specific_ids = array(37, 40, 53);

    if( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product->get_id() ) 
    && in_array( $product->get_id(), $specific_ids ) ) {
        $button_text = __("Custom text", "woocommerce");
    }
    return $button_text;
}

Code goes in functions.php file of your active child theme (or active theme). it should work.

Some related answers threads:

  • Change "add to cart" button for purchased products in Woocommerce
  • Custom add to cart button, if the customer has bought previously the product
  • Checking if customer has already bought something in WooCommerce


来源:https://stackoverflow.com/questions/61556600/change-add-to-cart-text-if-a-user-has-bought-specific-products-in-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!