prosource

사용자/게스트가 WooCommerce에서 특정 제품을 구입했는지 확인합니다.

probook 2023. 3. 9. 22:09
반응형

사용자/게스트가 WooCommerce에서 특정 제품을 구입했는지 확인합니다.

고객이 이전에 WooCommerce에서 특정 제품을 구매했는지 확인해야 합니다.

예를 들어 다음과 같습니다.고객은 제품 "a" 또는 "b"를 조기에 구매하지 않는 한 제품 "c", "d", "e"를 구매할 수 없습니다.

고객이 이전에 제품 "a" 또는 "b"를 구입한 경우 제품 "c", "d" 및 "e"의 구매 버튼이 활성화되어 구매가 허용된다.

이전에 "a" 또는 "b"를 구입하지 않은 경우 "c", "d", "e"를 구입할 수 없으며 구매 버튼이 비활성화됩니다.

어떻게 하면 좋을까요?

감사해요.

여러 제품 ID를 처리할 수 있는 보다 가볍고 개선된 코드 버전

갱신필 (Woocommerce 3+와의 호환성)

네, 현재 고객이 이미 특정 정의된 제품 ID를 구입한 경우 "참"을 반환하는 조건부 함수를 작성할 수 있습니다.이 코드는 기능합니다.php 파일에는 액티브한 아이 테마 또는 테마가 포함되어 있습니다.

조건부 함수는 다음과 같습니다.

function has_bought_items() {
    $bought = false;

    // Set HERE ine the array your specific target product IDs
    $prod_arr = array( '21', '67' );

    // Get all customer orders
    $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"
    ) );
    foreach ( $customer_orders as $customer_order ) {
        // Updated compatibility with WooCommerce 3+
        $order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id;
        $order = wc_get_order( $customer_order );

        // Iterating through each current customer products bought in the order
        foreach ($order->get_items() as $item) {
            // WC 3+ compatibility
            if ( version_compare( WC_VERSION, '3.0', '<' ) ) 
                $product_id = $item['product_id'];
            else
                $product_id = $item->get_product_id();

            // Your condition related to your 2 specific products Ids
            if ( in_array( $product_id, $prod_arr ) ) 
                $bought = true;
        }
    }
    // return "true" if one the specifics products have been bought before by customer
    return $bought;
}

이 코드는 테스트되어 동작합니다.


★★★
예를 들어 이전에 활성 하위 테마 또는 테마에 복사한 일부 WooCommerce 템플릿에서 사용할 수 있습니다.

  • [ Shop ]페이지의 [consuring]버튼 템플릿은 입니다.
  • 제품 페이지에 대한 단추 템플릿은 제품 유형에 따라 폴더에 있습니다.

위의 템플릿에서 사용할 수 있는 예를 다음에 나타냅니다.

// Replace the numbers by your special restricted products IDs
$restricted_products = array( '20', '32', '75' );

// compatibility with WC +3
$product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;

// customer has NOT already bought a specific product for this restricted products
if ( !has_bought_items() && in_array( $product_id, $restricted_products ) ) { 

    // Displaying an INACTIVE add-to-cart button (With a custom text, style and without the link).
    // (AND optionally) an explicit message for example.

// ALL OTHER PRODUCTS OR RESTRICTED PRODUCTS IF COSTUMER HAS ALREADY BOUGHT SPECIAL PRODUCTS
} else { 

    // place for normal Add-To-Cart button code here
}

다음Shop 페이지의 버튼 템플릿에 적용된 전체 입니다.

<?php
/**
 * Loop Add to Cart
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/loop/add-to-cart.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see         https://docs.woocommerce.com/document/template-structure/
 * @author      WooThemes
 * @package     WooCommerce/Templates
 * @version     2.5.0
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

global $product;

// Replace the numbers by your special restricted products IDs
$restricted_products = array( '37', '53', '70' );

// compatibility with WC +3
$product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;

if ( !has_bought_items() && in_array( $product_id, $restricted_products ) ) {

    echo '<a class="button greyed_button">' . __("Disabled", "your_theme_slug") . '</a>';
    echo '<br><span class="greyed_button-message">' . __("Your message goes here…", "your_theme_slug") . '</span>';

} else {

echo apply_filters( 'woocommerce_loop_add_to_cart_link',
    sprintf( '<a rel="nofollow" href="%s" data-quantity="%s" data-product_id="%s" data-product_sku="%s" class="%s">%s</a>',
        esc_url( $product->add_to_cart_url() ),
        esc_attr( isset( $quantity ) ? $quantity : 1 ),
        esc_attr( $product_id ),
        esc_attr( $product->get_sku() ),
        esc_attr( isset( $class ) ? $class : 'button' ),
        esc_html( $product->add_to_cart_text() )
    ),
$product );

}

활성 하위 테마 또는 테마 파일의 클래스로 비활성 단추를 스타일링합니다.수업 내용도 마찬가지야

2020 업데이트: 이제 게스트 사용자를 과금 전자 메일에서 처리합니다.

새로운 버전의 컴팩트, 경량, 고속, 모든 버전의 woocommerce (버전 2.4 이후)와 호환성이 있습니다.

이것은 부분적으로 내장된 woocommerce 함수 소스 코드를 기반으로 하는 새로운 확장 및 경량 조건부 함수입니다.

다음 2가지 옵션인수가 있습니다.

  • $user_var을 사용하다
  • 정의된 사용자 ID 지정(가 현재 로그인한 사용자에 대해 사용되지 않음)
  • 또는 게스트 사용자의 청구 이메일
  • $product_ids (어레이)는 체크할 제품 ID를 1개 또는 여러 개 지정할 수 있습니다.

이 코드는 다음과 같습니다.

function has_bought_items( $user_var = 0,  $product_ids = 0 ) {
    global $wpdb;
    
    // Based on user ID (registered users)
    if ( is_numeric( $user_var) ) { 
        $meta_key     = '_customer_user';
        $meta_value   = $user_var == 0 ? (int) get_current_user_id() : (int) $user_var;
    } 
    // Based on billing email (Guest users)
    else { 
        $meta_key     = '_billing_email';
        $meta_value   = sanitize_email( $user_var );
    }
    
    $paid_statuses    = array_map( 'esc_sql', wc_get_is_paid_statuses() );
    $product_ids      = is_array( $product_ids ) ? implode(',', $product_ids) : $product_ids;

    $line_meta_value  = $product_ids !=  ( 0 || '' ) ? 'AND woim.meta_value IN ('.$product_ids.')' : 'AND woim.meta_value != 0';

    // Count the number of products
    $count = $wpdb->get_var( "
        SELECT COUNT(p.ID) FROM {$wpdb->prefix}posts AS p
        INNER JOIN {$wpdb->prefix}postmeta AS pm ON p.ID = pm.post_id
        INNER JOIN {$wpdb->prefix}woocommerce_order_items AS woi ON p.ID = woi.order_id
        INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS woim ON woi.order_item_id = woim.order_item_id
        WHERE p.post_status IN ( 'wc-" . implode( "','wc-", $paid_statuses ) . "' )
        AND pm.meta_key = '$meta_key'
        AND pm.meta_value = '$meta_value'
        AND woim.meta_key IN ( '_product_id', '_variation_id' ) $line_meta_value 
    " );

    // Return true if count is higher than 0 (or false)
    return $count > 0 ? true : false;
}

코드는 기능합니다.php 파일 또는 임의의 플러그인 파일에 있는 활성 자식 테마(또는 테마)입니다.

이 코드는 WooCommerce 3+에서 테스트되어 동작합니다(이전 버전에서도 동작합니다).


사용 예:

1(고객에 로그인):현재 사용자가 정의된 제품 중 하나를 구입했는지 감지(제품 ID는 어레이여야 함)

// Define the targeted Products IDs
$product_ids = array( 38, 41, 85, 95 );

if( has_bought_items( '', $product_ids ) )
    echo "<p>You have already purchased one of this products</p>";
else
    echo "<p>You have not yet purchased one of this products</p>";

2(정의된 사용자 ID의 경우) 정의된 사용자가 정의된 제품 중 하나를 구입했는지 감지(제품 ID를 배열로 설정해야 함)

// Define the user ID
$user_id = 85;

// Define the targeted Products IDs
$product_ids = array( 38, 41, 85, 95 );

if( has_bought_items( $user_id, $product_ids ) )
    echo "<p>This user have already purchased one of this products</p>";
else
    echo "<p>This user have not yet purchased one of this products</p>";

경우,$user_id되어 있지 않고 않은 , 이 는 "이러한 사용자"를 합니다.false.

3(게스트 사용자의 경우) 게스트 사용자정의된 제품 중 하나를 과금 전자 메일에서 구입했는지 감지(제품 ID를 어레이로 설정해야 함)

// Define guest Billing email (string)
$user_email = 'louis.fourteen@gmail.com';

// Define the targeted Products IDs
$product_ids = array( 38, 41, 85, 95 );

if( has_bought_items( $user_email, $product_ids ) )
    echo "<p>This user have already purchased one of this products</p>";
else
    echo "<p>This user have not yet purchased one of this products</p>";

경우,$user_id되어 있지 않고 않은 , 이 는 "이러한 사용자"를 합니다.false.

4(고객에 로그인)현재 사용자가 이미 구입했는지 감지

if( has_bought_items() )
    echo '<p>You have already made a purchase</p>';
else
    echo '<p>Welcome, for your first purchase you will get a discount of 10%</p>';

5(사용자 ID 정의) - 정의된 사용자가 이미 구입했는지 감지

// Define the user ID
$user_id = 85;

if( has_bought_items( $user_id ) )
        echo '<p>customer have already made a purchase</p>';
    else
        echo '<p>Customer with 0 purshases</p>';

여기서 사용자 ID가 0이고 현재 사용자가 로그인하지 않은 경우 함수는 반환됩니다(게스트 사용자에 대해 과금 이메일이 정의되지 않은 경우).

"woocomme"wc_customer_bought_product이 경우에도 사용할 수 있습니다.

함수의 사용법을 참조해당 함수는 다음과 같습니다.

이런 식으로 하고 있어요.

woocommerce 합니다.woocommerce_is_purchasable

이게 다 기능이에요.

  1. .6는 "ID" 했습니다.2.6 + Woocommerce 。wc_customer_bought_product하기 위해 저는 적이 만, 해, 수.고객이 제품을 가지고왔는지를 합니다.

    function cmk_check_product_brought( $ids=array() ) {
        if ( ! $ids ) return false;
        foreach ( $ids as $product => $id ) {
            if ( wc_customer_bought_product( wp_get_current_user()->user_email, get_current_user_id(), $id ) ) {
                return true;
            }
        }
    }
    

이전에 고객으로부터 특정 제품 ID를 이미 가져왔는지 확인하는 방법은 아래와 같으므로, 제가 만든 것은 ID 배열이 아닙니다만, 이러한 기능 중 하나를 사용할 수 있습니다.

function cmk_product_ordered( $id ) {
    // Get All order of current user
    $orders = get_posts( array(
        'numberposts' => -1,
        'meta_key'    => '_customer_user',
        'meta_value'  => get_current_user_id(),
        'post_type'   => wc_get_order_types( 'view-orders' ),
        'post_status' => array_keys( wc_get_order_statuses() )
    ) );

    if ( !$orders ) return false; // return if no order found

    $all_ordered_product = array(); // store all products ordered by ID in an array

    foreach ( $orders as $order => $data ) { // Loop through each order
        $order_data = new WC_Order( $data->ID ); // create new object for each order
        foreach ( $order_data->get_items() as $key => $item ) {  // loop through each order item
            // store in array with product ID as key and order date a value
            $all_ordered_product[ $item['product_id'] ] = $data->post_date; 
        }
    }
    // check if defined ID is found in array
    if ( isset( $all_ordered_product[ $id ] ) ) return true;
    else return false;
}
  1. 이제 제품 ID를 이미 가져왔는지 확인할 수 있게 되었으니 필터만 추가하면 됩니다.woocommerce_is_purchasable우리의 조건을 만들기 위해, 아래의 함수는 당신이 달성하려는 것의 단순한 예입니다.

방금 변경했습니다.$required_purchased그리고.$conditional_purchase가치.

function cmk_disable_product_purchase( $purchasable, $product ) {

    // array of products required to be purchase first
    $required_purchased = array( 1, 2);

    // array of restricted/conditional products to be purchase
    $conditional_purchase = array( 3,4,5);

    // Get the ID for the current product
    $product_id = $product->is_type( 'variation' ) ? $product->variation_id : $product->id;

    //return default $purchasable if current product ID is not in restricted array
    if ( !in_array($product_id, $conditional_purchase)) return $purchasable;

    /**
     ** Check if one required products has been purchase;
     **/

    // using cmk_check_product_brought() function, return false if product is not purchase
    if ( ! cmk_check_product_brought( $required_purchased ) ) $purchasable = false;

    // using cmk_product_ordered() function, you can use this instead
    /*if ( cmk_product_ordered( 1 )  || cmk_product_ordered( 2 ) ) {
        $purchasable = $purchasable; //return default if one product is purchased
    } else {
        $purchasable = false;
    }*/

    // Double-check for variations: if parent is not purchasable, then variation is not
    if ( $purchasable && $product->is_type( 'variation' ) ) {
        $purchasable = $product->parent->is_purchasable();
    }

    return $purchasable;
}
add_filter( 'woocommerce_variation_is_purchasable', 'cmk_disable_product_purchase', 10, 2 );
add_filter( 'woocommerce_is_purchasable', 'cmk_disable_product_purchase', 10, 2 );

그러면 제품이 구매 불가로 설정됩니다(카트에 추가 버튼은 자동으로 숨겨집니다).구매 불가능한 제품에 대한 메시지를 추가하고 싶다면 동일한 조건을 사용할 수 있습니다.cmk_disable_product_purchase메시지를 추가하고 연결하기만 하면 됩니다.woocommerce_single_product_summary또는 원하는 위치에 표시할 수 있습니다.

언급URL : https://stackoverflow.com/questions/38769888/check-if-a-user-guest-has-purchased-specific-products-in-woocommerce

반응형