2017-01-16 4 views
2

В WooCommerce мне нужно знать, есть ли возможность изменить кнопку «Добавить в корзину», если клиент купил ранее продукт.Пользовательская кнопка добавления в корзину, если клиент купил ранее продукт

Мы продаем онлайн-курсы через WooCommerce & Членство, поэтому идея заключается в том, что если клиент не купил курс, ему нужно увидеть кнопку «Магазин сейчас». Но если он купил курс, он должен увидеть кнопку «Открыть сейчас» с пользовательской ссылкой для каждого продукта (курса).

Как я могу это достичь?

Спасибо.

ответ

1

Ниже решения добавить его в functions.php и работать. Когда заказ будет завершен, кнопка будет изменена.

add_filter('woocommerce_loop_add_to_cart_link','add_to_cart_link_customer_has_bought'); 

    function add_to_cart_link_customer_has_bought() { 

     global $product; 

     if(empty($product->id)){ 

      $wc_pf = new WC_Product_Factory(); 
      $product = $wc_pf->get_product($id); 

     } 

     $current_user = wp_get_current_user(); 

     if(wc_customer_bought_product($current_user->user_email, $current_user->ID, $product->id)){ 

      $product_url = get_permalink(); 
      $button_label = "View Product"; 

     } else { 

      $product_url = $product->add_to_cart_url(); 
      $button_label = $product->add_to_cart_text(); 

     }; 

     echo sprintf('<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" data-quantity="%s" class="button %s product_type_%s">%s</a>', 
      esc_url($product_url), 
      esc_attr($product->id), 
      esc_attr($product->get_sku()), 
      esc_attr(isset($quantity) ? $quantity : 1), 
      $product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '', 
      esc_attr($product->product_type), 
      esc_html($button_label) 
     ); 

    } 
+0

Ничего себе, спасибо! И еще один вопрос, после использования этого кода, где я могу изменить URL-адрес, который должен был бы перенаправить кнопку? Можно ли установить другую ссылку для каждого продукта и как я могу это сделать? – Melania

+0

Какая ссылка? куда он должен идти? Ссылка вы можете разместить здесь 'esc_url ($ product_url)', но мы должны знать, какая это ссылка? – mattkrupnik

2

Вот полностью работоспособны и тестирование пользовательской функции, которая будет отображаться на цеховых страницы и архивы WooCommerce страниц, пользовательские дополнения к тележке (текст + ссылка), для зарегистрированных в клиентов, которые уже купили продукты :

add_filter('woocommerce_loop_add_to_cart_link', 'customizing_add_to_cart_button', 10, 2); 
function customizing_add_to_cart_button($link, $product){ 

    $bought = false; 

    if(is_user_logged_in()){ 

     $customer_orders = get_posts(array(
      'numberposts' => -1, 
      'meta_key' => '_customer_user', 
      'meta_value' => get_current_user_id(), 
      'post_type' => 'shop_order', // WC orders post type 
      'post_status' => 'wc-completed' // Only orders with status "completed" 
     )); 

     // Going through each current customer orders 
     foreach ($customer_orders as $customer_order) { 
      $order = wc_get_order($customer_order->ID); 
      // Going through each current customer order items 
      foreach($order->get_items() as $item_id => $item_values){ 
       if($item_values['product_id'] == $product->id){ 
        $bought = true; 
        break; 
       } 
      } 
     } 
    } 

    if($bought){ 

     // ==> SET HERE YOUR 
     // CUSTOM ADD TO CART text and link 
     $add_to_cart_url = site_url('/custom_link/'); 
     $button_text = __('View now', 'woocommerce'); 

    } else { 

     $add_to_cart_url = $product->add_to_cart_url(); 
     $button_text = $product->add_to_cart_text(); 

    } 

    $link = sprintf('<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" data-quantity="%s" class="button product_type_%s">%s</a>', 
     esc_url($add_to_cart_url), 
     esc_attr($product->id), 
     esc_attr($product->get_sku()), 
     esc_attr(isset($quantity) ? $quantity : 1), 
     esc_attr($product->product_type), 
     esc_html($button_text) 
    ); 

    return $link; 
} 

Этот код идет в function.php файле вашего активного ребенка темы (или темы), или также в любой файл плагина.


Если вы хотите настроить кнопку дополнения к тележке для некоторых конкретных продуктов или массив продуктов или категорию продукта, вам придется добавить условие на конкретный продукт, таким образом (это является выпиской из вышеуказанного кода):

if($bought){ 

     // for the product ID 45 (for example) 
     if($product->id == 45){ 
      $add_to_cart_url = site_url('/custom-link/product-45/'); 
      $button_text = __('View now product 45', 'woocommerce'); 
     } 

     // for the product ID 64 (for example) 
     if($product->id == 64){ 
      $add_to_cart_url = site_url('/custom-link/product-64/'); 
      $button_text = __('View now product 64', 'woocommerce'); 
     } 

     // for an array of product IDs (for example) 
     $product_ids = array(89, 92, 124); 
     if(in_array($product->id, $product_ids)){ 
      $add_to_cart_url = site_url('/custom-link/some-products/'); 
      $button_text = __('View now some products', 'woocommerce'); 
     } 
     // for a product category 
     // set here your product category ID, slug or name (or an array of values) 
     $category = 'My category'; // Here a category name for example 
     if(has_term($category, 'product_cat', $product->id)){ 
      $add_to_cart_url = site_url('/custom-link/my-category/'); 
      $button_text = __('View now from my category', 'woocommerce'); 
     } 
    } else { 

     $add_to_cart_url = $product->add_to_cart_url(); 
     $button_text = $product->add_to_cart_text(); 

    }