Display a text in all products if user has purchased a specific product

Viewed 39

The code below displays a message on the product page that has the "free" tag to the logged in user

  function add_text_after_excerpt_single_product_free2( $short_description ) {
    global $product;
    $terms = get_the_terms( $product->get_id(), 'product_tag' );

    foreach ( $terms as $term ) {

        if ( $term->name == 'Free' && is_user_logged_in() ) {
            $short_description .= 'Downloading this file is free and does not require subscription';
        }

    }

    return $short_description;
}
add_filter('woocommerce_short_description','add_text_after_excerpt_single_product_free2', 20, 1);

I want the above code to be executed if a user has purchased a specific product

For example, a user buys a product called Photoshop training, and from now on the above code will be executed for him

thanx

2 Answers

You can write a custom function to check whether user buy a specific product. Try the below code. code will go in your active theme functions.php file.

This below function is inspired from here - Check if a user/guest has purchased specific products in WooCommerce

function has_bought_items( $user_id = 0,  $product_ids = 0 ) {
    global $wpdb;
    
    // Based on user ID (registered users)
    $meta_key   = '_customer_user';
    $meta_value = $user_id; 
    
    $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;
}

function add_text_after_excerpt_single_product_free2( $short_description ) {    
    // Define the targeted specific Products IDs
    $product_ids = array( 74 );

    if ( is_user_logged_in() && has_bought_items( get_current_user_id(), $product_ids ) ) {
        $short_description .= 'Downloading this file is free and does not require subscription';
    }

    return $short_description;
}
add_filter( 'woocommerce_short_description','add_text_after_excerpt_single_product_free2', 20, 1 );

Tested and works

enter image description here

Related