WooCommerce Developer FAQ Part 1

Hello everyone! In this article, I decided to collect the most frequently asked questions about working with WooCommerce for developers. This is the first part of my FAQ, which covers key aspects that will help you better navigate this popular tool. Let's get started!

1. Working with the basket

1.1. Adding a product to the cart

<?php
$product_id = 123; // Замените на ID вашего продукта
$quantity = 1; // Количество товара

WC()->cart->add_to_cart($product_id, $quantity);

1.2. Receiving all items in the basket

<?php
$cart_items = WC()->cart->get_cart();
    
foreach ($cart_items as $cart_item_key => $cart_item) {
    $product_id = $cart_item['product_id'];
    $quantity = $cart_item['quantity'];
    $product_name = $cart_item['data']->get_name(); // Получаем название продукта

    echo 'Товар: ' . $product_name . ' - Количество: ' . $quantity . '<br>';
}

1.3. Removing an item from the cart

<?php
$cart_item_key = 123; // Замените на key вашего продукта из корзины

WC()->cart->remove_cart_item($cart_item_key);

1.4. Updating the quantity of goods in the basket

<?php
$cart_item_key = 123; // Замените на key вашего продукта из корзины
$quantity = 10; // Количество товара

WC()->cart->set_quantity($cart_item_key, $quantity);

1.5. How to get cart_item_key a specific product in the basket

<?php

$product_id = 123; // Замените на ваш ID товара

// Получите все элементы в корзине
$cart_items = WC()->cart->get_cart();

// Переберите все элементы и найдите соответствие по product_id
$cart_item_key = null;

foreach ( $cart_items as $key => $item ) {
    if ( $item['product_id'] == $product_id ) {
        $cart_item_key = $key; // Сохраните ключ элемента
        break; // Выход из цикла, если найдено совпадение
    }
}

echo $cart_item_key;

1.6. Number of items in the basket

<?php
echo WC()->cart->get_cart_contents_count();

1.7. Link to the cart page

<?php
echo wc_get_cart_url();

2. Working with the product

2.1. Obtaining information about the product

<?php
$product_id = 123; // Замените на ваш ID товара
$product = wc_get_product( $product_id );

if ( $product ) {
    echo 'Название продукта: ' . $product->get_name();
    echo 'Артикул: ' . $product->get_sku();
    echo 'Цена: ' . $product->get_price();
    echo 'Описание: ' . $product->get_description();
} else {
    echo 'Продукт не найден.';
}

2.2. Creating a new product

<?php
$product = new WC_Product_Simple();
$product->set_name( 'Имя продукта' );
$product->set_regular_price( '19.99' );
$product->set_description( 'Описание продукта' );
$product->set_stock_quantity( 100 );
$product->set_status( 'publish' ); // Или 'draft' для хранения в черновиках

$product_id = $product->save(); // Сохраняем продукт и получаем его ID
echo 'Создан продукт с ID: ' . $product_id;

2.3. Updating an existing product

<?php

$product_id = 123; // Замените на ваш ID товара
$product = wc_get_product( $product_id );

if ( $product ) {
    $product->set_price( '24.99' ); // Обновите цену
    $product->set_stock_quantity( 80 ); // Обновите количество на складе
    $product->save(); // Сохраняем изменения
    echo 'Продукт обновлён.';
} else {
    echo 'Продукт не найден.';
}

2.4.Removing the product

<?php
$product_id = 123; // Замените на ваш ID товара

// Убедитесь, что продукт существует
$product = wc_get_product( $product_id );
if ( $product ) {
    wp_delete_post( $product_id, true ); // true для полного удаления поста
    echo 'Продукт удалён.';
} else {
    echo 'Продукт не найден.';
}

2.5 Receiving all products

<?php
$args = array(
    'post_type' => 'product',
    'posts_per_page' => -1, // Получить все продукты
);
$query = new WP_Query( $args );

if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        $product = wc_get_product( get_the_ID() );
        echo 'ID: ' . $product->get_id() . ' Название: ' . $product->get_name() . '<br>';
    }
    wp_reset_postdata();
} else {
    echo 'Продукты не найдены.';
}

3. Working with the order

3.1 Receiving all orders

<?php

$status="completed";

$args = array(
  'status' => $status,
  'limit' => -1, // Получить все заказы
);

$orders = wc_get_orders($args);

foreach ($orders as $order) {
    echo 'Заказ #: ' . $order->get_id() . '<br>';
}

3.2. Obtaining data on a specific order

<?php
$order_id = 123; // Замените на ваш ID заказа
$order = wc_get_order($order_id);

if ($order) {
    echo 'Заказ ID: ' . $order->get_id() . '<br>';
    echo 'Состояние заказа: ' . $order->get_status() . '<br>';
    echo 'Сумма заказа: ' . $order->get_total() . '<br>';
} else {
    echo 'Заказ не найден.';
}

3.3. Changing the order status

pending — Waiting for payment
processing — In processing
on-hold — On hold
completed — Completed
cancelled – Cancelled
refunded – Returned

<?php
$order_id = 123; // Замените на ваш ID заказа
$order = wc_get_order( $order_id );

if ( $order ) {
    $new_status="completed"; // Замените на нужный вам статус (например, 'pending', 'processing', 'on-hold', 'completed', 'cancelled', 'refunded', 'failed')
    $order->update_status( $new_status, 'Статус заказа обновлён на ' . $new_status );
    echo 'Статус заказа был изменён на ' . $new_status;
} else {
    echo 'Заказ не найден.';
}

3.4. Deleting an order

<?php
$order_id = 123; // Замените на ваш ID заказа
$order = wc_get_order($order_id);

if ($order) {
    $order->delete(true);
    echo 'Заказ ID: ' . $order_id . ' был удалён.';
} else {
    echo 'Заказ не найден.';
}

3.5. Changing customer data in an order

<?php
$order_id = 123; // Замените на ваш ID заказа
$order = wc_get_order($order_id);

if ($order) {
    $order->set_billing_address_1('new_address');
    $order->set_billing_city('new_city');
    $order->set_billing_postcode('new_postcode');
    $order->save();
    echo 'Адрес доставки обновлён для заказа ID: ' . $order_id;
} else {
    echo 'Заказ не найден.';
}

If you have any questions or want to share your experience on this topic, feel free to leave a comment! I'd love to hear your opinion. Thank you for your attention!

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *