آموزش سفارش نمونه رایگان محصول در ووکامرس

اگر قصد دارید برای هر محصول خود یک نمونه رایگان قرار دهید تا مشتری ها بتوانند تست نمایند ، آموزش زیر را مطالعه کنید
برای سفارش نمونه رایگان در ووکامرس ابتدا باید مراحل زیر را انجام دهید
یک محصول نمونه جدید دقیقا با نام “نمونه رایگان” ایجاد کنیم.
الزامات:
عنوان: “نمونه رایگان”
قیمت: صفر
قابلیت مشاهده کاتولوگ: “پنهان”
فهرست موجودی: “فروخته شده به صورت تکی”
سپس کد زیر را در functions.php قرار دهید
// -------------------------
// 1. Display Free Sample Add to Cart
// Note: change "12345" with Free Sample ID
add_action( 'woocommerce_single_product_summary', 'a4fran3_add_free_sample_add_cart', 35 );
function a4fran3_add_free_sample_add_cart() {
?>
<form class="cart" method="post" enctype='multipart/form-data'>
<button type="submit" name="add-to-cart" value="12345" class="single_add_to_cart_button button alt">Order a Free Sample</button>
<input type="hidden" name="free_sample" value="<?php the_ID(); ?>">
</form>
<?php
}
// -------------------------
// 2. Add the custom field to $cart_item
add_filter( 'woocommerce_add_cart_item_data', 'a4fran3_store_free_sample_id', 10, 2 );
function a4fran3_store_free_sample_id( $cart_item, $product_id ) {
if( isset( $_POST['free_sample'] ) ) {
$cart_item['free_sample'] = $_POST['free_sample'];
}
return $cart_item;
}
// -------------------------
// 3. Preserve the custom field in the session
add_filter( 'woocommerce_get_cart_item_from_session', 'a4fran3_get_cart_items_from_session', 10, 2 );
function a4fran3_get_cart_items_from_session( $cart_item, $values ) {
if ( isset( $values['free_sample'] ) ){
$cart_item['free_sample'] = $values['free_sample'];
}
return $cart_item;
}
// -------------------------
// 4. Concatenate "Free Sample" with product name (CART & CHECKOUT)
add_filter( 'woocommerce_cart_item_name', 'a4fran3_alter_cart_item_name', 10, 3 );
function a4fran3_alter_cart_item_name( $product_name, $cart_item, $cart_item_key ) {
if ( $product_name == "Free Sample" ) {
$product = wc_get_product( $cart_item["free_sample"] );
$product_name .= " (" . $product->get_name() . ")";
}
return $product_name;
}
// -------------------------
//a4fran3.ir: 5. Add "Free Sample" product name to order meta
// Note: this will show on thank you page, emails and orders
add_action('woocommerce_add_order_item_meta','a4fran3_save_posted_field_into_order', 10, 2);
function a4fran3_save_posted_field_into_order( $itemID, $values ) {
if ( !empty( $values['free_sample'] )) {
$product = wc_get_product( $values['free_sample'] );
$product_name .= " (" . $product->get_name() . ")";
wc_add_order_item_meta( $itemID, 'Free sample for', $product_name );
}
}
نتیجه کد بالا :











