Пользовательский номер заказа WooCommerce с добавлением артикул продуктаPhp

Кемеровские программисты php общаются здесь
Ответить
Anonymous
 Пользовательский номер заказа WooCommerce с добавлением артикул продукта

Сообщение Anonymous »

Я создаю интернет-магазин WooCommerce с разными вариантами и хочу получать разные серии номеров заказов или номеров счетов на основе этой темы.
Мне нужно похожее решение. Коды, которые я пробовал:
Первая попытка
add_filter( 'woocommerce_order_number', 'change_woocommerce_order_number' );

function change_woocommerce_order_number( $order_id ) {
$order = new WC_Order( $order_id );
foreach ( $order->get_items() as $item_key => $item )
$product = $order->get_product_from_item( $item );
$sku = $product->get_sku();
$new_order_id = $sku . $order_id;
return $new_order_id;
}

Вторая попытка:
function change_woocommerce_order_number($order_id) {
$order = new WC_Order($order_id);
$items = $order->get_items();
$first_item = $items[0];
$product_id = $first_item->get_product_id();
$product = new WC_Product($product_id);
$sku = $product->get_sku();

return $sku.$order_id;
}
add_filter('woocommerce_order_number', 'change_woocommerce_order_number');

Теперь, когда я использую эти фрагменты кода, страница оформления заказа перестает работать и выдает ошибку «на этом веб-сайте произошла критическая ошибка». Я полный новичок в пользовательском кодировании.
Изменить:
Я обнаружил, что приведенный ниже код работает. как я хочу, а также последовательно увеличивать номер заказа, добавляя настраиваемое поле, которое действует как счетчик, но мне придется добавить этот код для каждого продукта отдельно
add_filter( 'woocommerce_order_number', 'custom_wc_order_number_increment_with_meta', 10, 2 );
function custom_wc_order_number_increment_with_meta( $order_id, $order ) {
$item = current( $order->get_items() ); // Get the first order item
$product = $item->get_product(); // Get the WC_Product Object
$product_id = $product->get_id(); // Get the product ID
$sku = $product->get_sku(); // Get the SKU from the product

// Specify the product ID you want to target
$target_product_id = 1234; // Replace with the actual product ID

if ( $product_id == $target_product_id && $sku ) {
// Retrieve the current order number from post meta (custom field)
$current_order_number = get_post_meta( $product_id, '_custom_order_number', true );

// If no order number is found in the meta, start from 1
if ( empty( $current_order_number ) ) {
$current_order_number = 1;
}

// Customize the order number by prepending SKU and using the incremented number
$custom_order_number = $sku . '-' . str_pad($current_order_number, 4, '0', STR_PAD_LEFT); // Example: SKU-0001

// Increment the number for the next order
$new_order_number = $current_order_number + 1;

// Update the incremented number in the product's post meta
update_post_meta( $product_id, '_custom_order_number', $new_order_number );

return $custom_order_number;
}

return $order_id; // Return default order ID if it's not the target product
}


Подробнее здесь: https://stackoverflow.com/questions/791 ... roduct-sku
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Php»