Includes reusable code snippets to display specific ACF data based on customer purchases.
Step 1: Go and Add Add Required ACF fields and set the location to “Products†– Please copy the “Name Field of ACF fields and save.
- Add this PHP Snippet. This code will get Last Product purchased ID of customer & Link it with ACF. So It will give us a shortcode that we can use. So If a customer has bought product one and then we can use the shortcode it will show the ACF data that was added in respective product.
Short Code:
[acf_product_field field="add-any-acf-field-name"]
For example: [acf_product_field field="amazon_basket_link"]
PHP Code:
function get_user_last_product_id() {
$customer_orders = wc_get_orders([
'customer_id' => get_current_user_id(),
'limit' => 1,
'orderby' => 'date',
'order' => 'DESC',
]);
if (empty($customer_orders)) return false;
$order = $customer_orders[0];
foreach ($order->get_items() as $item) {
return $item->get_product_id();
}
return false;
}
function shortcode_acf_product_field($atts) {
$atts = shortcode_atts([
'field' => ''
], $atts);
$product_id = get_user_last_product_id();
if (!$product_id || empty($atts['field'])) return '';
return get_field($atts['field'], $product_id);
}
add_shortcode('acf_product_field', 'shortcode_acf_product_field');
