Reading list Switch to dark mode

    How to Master WooCommerce Development with CRUD Objects?

    Updated 12 April 2024

    In this dev blog post, we will learn about how WooCommerce development with CRUD objects works.

    As you may already know WooCommerce is a vital part of the WordPress e-commerce world that supports online businesses globally.

    So to enhance your WooCommerce skills, mastering CRUD (Create, Read, Update, and Delete) operations is crucial for efficient object management.

    This article delves into how to master WooCommerce CRUD objects, their significance, and practical use in development, with illustrative examples for your journey to WooCommerce mastery.

    Understanding WooCommerce CRUD Objects

    WooCommerce CRUD objects are pivotal in WooCommerce development, offering a structured way to interact with data such as products, orders, and customers.

    Searching for an experienced
    Woocommerce Company ?
    Find out More

    These objects enable vital CRUD operations for managing records within the WooCommerce database.

    Key WooCommerce CRUD Objects

    1. WC_Product: This entity signifies a core element within WooCommerce, dedicated to overseeing and handling crucial product data for a seamless e-commerce experience.

    2. WC_Order: The WC_Order object is essential for handling customer orders, including order details, customer information, and order status.

    3. WC_Customer: WC_Customer objects serve as a pivotal tool for engaging with customer data, empowering WooCommerce developers to efficiently craft and oversee customer accounts within the WooCommerce ecosystem.

    4. WC_Coupon: Maximizing WooCommerce Coupons with WC_Coupon: Empower developers to seamlessly craft and apply discounts, elevating the shopping experience for your customers.

    5. WC_Shipping_Method: For tailored shipping solutions, rely on WC_Shipping_Method objects to define shipping choices and rates, offering flexibility and customization in the world of WooCommerce.

    Advantages of Leveraging WooCommerce CRUD Objects

    Understanding and utilizing CRUD objects in your WooCommerce development projects offers several benefits:

    Data Management

    CRUD operations allow you to effectively manage your e-commerce data. You can create new products, read product information, update product details, and delete products that are no longer needed.

    Product Management

    With WooCommerce, you can easily create and manage your product catalog. You can add new products, update product prices, descriptions, and images, and delete products that are discontinued or out of stock.

    Order Processing

    CRUD operations enable you to manage customer orders efficiently. You have the capability to generate new orders, access comprehensive order information, modify order statuses, and execute cancellations or deletions as required.

    Customer Management

    WooCommerce allows you to create and manage customer accounts. You can add new customers, view customer profiles, update customer information, and delete customer accounts if required.

    Inventory Control

    CRUD operations help you keep track of your product inventory. You can manage stock quantities, restock products as needed, and remove discontinued items from your inventory.

    Data Integrity

    By using CRUD operations, you can ensure data integrity within your WooCommerce store. You can maintain accurate product information, order records, and customer data.

    Automation

    Many CRUD operations in WooCommerce can be automated through plugins and scripts.

    As an example, you can set up automated stock level adjustments, optimize order processing efficiency, and enable customer notification features.

    Improved User Experience

    By efficiently managing your store’s data using CRUD operations, you can provide a better user experience for your customers.

    They can easily find products, place orders, and receive order updates.

    Scalability

    As your e-commerce business grows, CRUD operations help you scale your operations.

    You can add new products and manage larger volumes of data without significant manual effort.

    Data Analysis

    Access to CRUD operations empowers you to extract and analyze essential data from your WooCommerce store, enabling informed business decisions.

    Like identifying top-selling products, understanding customer behavior, and optimizing pricing strategies for success.

     Practical Examples

    1. CRUD with Custom Product

    To craft a personalized product using the WC_Product object, utilize the provided code snippet:

    // Define the product data
    $wk_product_data = array(
        'name' => 'Wk Custom Product', // Name of your product
        'type' => 'simple', // Product type (simple, variable, etc.)
        'regular_price' => '19.99', // Regular price
        'description' => 'This is a wk custom product.', // Product description
        // Add more product attributes as needed
    );
    
    // Create a new product
    $wk_product = wc_get_product();
    
    // Set the product data
    $wk_product->set_props($wk_product_data);
    
    // Save the product
    $wk_product->save();
    

    This code will create a simple product with the specified data. You can customize the product attributes based on your requirements.

    To read a product, you can use the wc_get_product function and pass the product’s ID:

    $wk_product_id = 123; // Replace with the actual product ID
    $wk_product = wc_get_product($product_id);
    
    // Access product data
    $wk_product_name = $wk_product->get_name();
    $wk_product_price = $wk_product->get_regular_price();
    // Access more product data as needed
    

    Replace 123 with the actual product ID you want to read.

    To update a product, retrieve the product object and set new values for its properties:

    $wk_product_id = 123; // Replace with the actual product ID
    $wk_product = wc_get_product($wk_product_id);
    
    // Update product data
    $wk_product->set_name('New Wk Product Name');
    $wk_product->set_regular_price('39.99');
    $wk_product->set_description('Updated wk custom product description.');
    // Update more product data as needed
    
    // Save the updated product
    $wk_product->save();
    

    To delete a product, you can use the wp_delete_post function with the product’s ID:

    $wk_product_id = 123; // Replace with the actual product ID
    wp_delete_post($wk_product_id, true);
    

    This will permanently delete the product.

    2. Custom CRUD Order

    To create a new order in WooCommerce, you need to create an instance WC_Order and then set the order’s properties. Here’s an example:

    // Create a new order
    $wk_order = wc_create_order();
    
    // Add products to the order (replace with actual product IDs and quantities)
    $wk_product_id_1 = 123;
    $wk_product_id_2 = 456;
    $wk_order->add_product(wc_get_product($wk_product_id_1), 2); // Add 2 of product 1
    $wk_order->add_product(wc_get_product($wk_product_id_2), 1); // Add 1 of product 2
    
    // Set customer information (replace with actual customer data)
    $wk_order->set_billing_address(array(
        'first_name' => 'John',
        'last_name'  => 'Doe',
        'email'      => '[email protected]',
        'phone'      => '123-456-7890',
    ));
    
    // Calculate totals
    $wk_order->calculate_totals();
    
    // Save the order
    $wk_order->save();
    

    This code creates a new order, adds products to it, sets customer information, calculates totals, and saves the order.

    To read an order, you can retrieve it using the order ID:

    $wk_order_id = 1; // Replace with the actual order ID
    $wk_order = wc_get_order($wk_order_id);
    
    // Get order data
    $wk_order_status = $wk_order->get_status();
    $wk_order_total = $wk_order->get_total();
    // Access more order data as needed
    

    This code retrieves the order and allows you to access its information.

    To update an existing order, retrieve the order object and set new values for its properties:

    $wk_order_id = 1; // Replace with the actual order ID
    $wk_order = wc_get_order($wk_order_id);
    
    // Update order data
    $wk_order->set_status('processing'); // Change order status
    $wk_order->set_customer_note('Updated customer note'); // Update customer note
    // Update more order data as needed
    
    // Calculate totals (if necessary)
    $wk_order->calculate_totals();
    
    // Save the updated order
    $wk_order->save();
    

    This code updates the order’s status, customer notes, and other data if needed.

    Deleting an order in WooCommerce can be a complex operation, as it might involve dealing with related data like order items, payments, and more.

    Here’s a simplified example that marks an order as cancelled:

    $wk_order_id = 1; // Replace with the actual order ID
    $wk_order = wc_get_order($wk_order_id);
    
    // Mark the order as canceled
    $wk_order->update_status('cancelled');
    

    This code changes the order status to “canceled.” It usually doesn’t permanently delete orders to maintain order history in WooCommerce.

    3. Customer Custom CRUD

    To generate a custom customer with the WC_Customer object, employ the provided code snippet:

    // Create a new customer object
    $wk_customer = new WC_Customer();
    
    // Set customer data
    $wk_customer->set_email('[email protected]');
    $wk_customer->set_first_name('John');
    $wk_customer->set_last_name('Doe');
    $wk_customer->set_password('password123'); // Set a password for the customer
    
    // Save the customer
    $wk_customer->save();
    

    This code creates a new custom customer with the specified data.

    To read a customer, you can use the WC_Customer class or the get_user_by function:

    // Option 1: Using WC_Customer
    $wk_customer_id = 1; // Replace with the actual customer ID
    $wk_customer = new WC_Customer($customer_id);
    // Store customer data in variables as your preference
    $wk_email = $wk_customer->get_email();
    $wk_first_name = $wk_customer->get_first_name();
    $wk_last_name = $wk_customer->get_last_name();
    
    // Option 2: Using get_user_by
    $wk_email = '[email protected]'; // Replace with the customer's email
    $wk_customer = get_user_by('email', $wk_email);
    
    if ($wk_customer && $wk_customer instanceof WC_Customer) {
        $wk_customer_id = $wk_customer->get_id();
        $wk_first_name = $wk_customer->get_first_name();
        $wk_last_name = $wk_customer->get_last_name();
    }
    

    Choose the method that best suits your needs, be it by customer ID or email.

    To update a customer, retrieve the customer object and set new values for its properties:

    $wk_customer_id = 1; // Replace with the actual customer ID
    $wk_customer = new WC_Customer($wk_customer_id);
    
    // Update customer data
    $wk_customer->set_first_name('New Jhon');
    $wk_customer->set_last_name('New Doe');
    $wk_customer->set_billing_phone('123-456-7890'); // Update other customer data as needed
    
    // Save the updated customer
    $wk_customer->save();
    

    This code updates the customer’s information.

    To delete a customer, you can use the wp_delete_user function:

    $wk_customer_id = 1; // Replace with the actual customer ID
    wp_delete_user($wk_customer_id, true);
    

    This will permanently delete the WooCommerce customer and associated data.

    4. CRUD with Custom Coupon

    Here’s the code snippet again for creating a coupon:

    // Create a new coupon
    $wk_data = array(
        'code' => 'WKNEWCOUPON',
        'amount' => '10',
        'discount_type' => 'percent', // or 'fixed_cart'
        // Add other coupon fields as needed
    );
    
    $wk_response = wc_rest_api_post('coupons', $wk_data);
    

    To read a coupon, you can use the wc_rest_api_get function:

    // Read a coupon by ID
    $wk_coupon_id = 786;
    $response = wc_rest_api_get("coupons/$wk_coupon_id");
    

    Update a coupon, and utilize the customer wc_rest_api_put function.

    // Update a coupon by ID
    $wk_coupon_id = 786;
    $wk_data = array(
        'amount' => '15',
        // Add other fields to update
    );
    
    $wk_response = wc_rest_api_put("coupons/$wk_coupon_id", $data);
    

    To delete a coupon, you can use the wc_rest_api_delete function:

    // Delete a coupon by ID
    $wk_coupon_id = 786;
    $response = wc_rest_api_delete("coupons/$wk_coupon_id");
    

    This will permanently delete the coupon and associated data. You can create a helper function wc_rest_api_post(), wc_rest_api_get(), wc_rest_api_put(), and wc_rest_api_delete() to make API requests using the WordPress HTTP API functions or libraries like Guzzle.

    5. Crud with Shipping Method

    You can create a custom shipping method in WooCommerce by adding a custom plugin. Here’s an example:

    <?php 
    /**
     * Plugin Name: Webkul WooCommerce Test Shipping 
     * Description: WooCommerce plugin to add custom shipping methods.
     * Version: 1.0.0
     * Plugin URI: http://webkul.com
     * Author: Webkul
     * Author URI: http://webkul.com
     * Text Domain: wk_wo_test_shipping
     * Domain Path: /languages
     *
     * Requires at least: 5.0
     * Requires PHP: 7.3
     * WC requires at least: 5.0
     * WC tested up to: 8.0
     *
     *
     * Requires Plugins: woocommerce
     *
     * @package Webkul WooCommerce Test Shipping 
     */
    // Define a function to add a custom shipping method
    function wk_add_custom_shipping_method() {
        $wk_method_id = 'custom_shipping'; // Unique ID for your shipping method
        $wk_method_title = 'Custom Shipping'; // Displayed title for your shipping method
    
        $wk_instance = new WC_Shipping_Method_Custom_Shipping();
    
        $wk_instance->id = $wk_method_id;
        $wk_instance->method_title = $wk_method_title;
    
        // Add settings for your custom shipping method
        $wk_instance->init_settings();
    
        // Register your shipping method
        WC()->shipping->register_shipping_method($wk_instance);
    }
    
    // Hook to add the custom shipping method
    add_action('woocommerce_shipping_init', 'wk_add_custom_shipping_method');
    
    // Define the custom shipping method class
    class Wk_Wc_Test_Shipping_Method_Custom_Shipping extends WC_Shipping_Method {
        public function __construct() {
            $this->id = 'custom_shipping'; // Unique ID for your shipping method
            $this->method_title = 'Custom Shipping'; // Displayed title for your shipping method
            $this->method_description = 'Custom Shipping Method Description'; // Description
    
            // Add settings for your custom shipping method
            $this->wk_init_form_fields();
            $this->init_settings();
    
            $this->enabled = $this->get_option('enabled');
    
            // Define the shipping rates and settings
            $this->title = $this->get_option('title');
            $this->cost = $this->get_option('cost');
    
            // Hook to calculate shipping costs
            add_action('woocommerce_calculate_shipping', array($this, 'wk_calculate_shipping'));
        }
    
        public function wk_init_form_fields() {
            $this->form_fields = array(
                'enabled' => array(
                    'title' => 'Enable',
                    'type' => 'checkbox',
                    'label' => 'Enable this shipping method',
                    'default' => 'yes',
                ),
                'title' => array(
                    'title' => 'Title',
                    'type' => 'text',
                    'description' => 'Title for this shipping method',
                    'default' => 'Custom Shipping',
                ),
                'cost' => array(
                    'title' => 'Cost',
                    'type' => 'text',
                    'description' => 'Shipping cost',
                    'default' => '10.00',
                ),
            );
        }
    
        public function wk_calculate_shipping($package) {
            // Calculate shipping cost here based on your logic
            $wk_rate = array(
                'id' => $this->id,
                'label' => $this->title,
                'cost' => $this->cost,
            );
    
            $this->add_rate($wk_rate);
        }
    }
    
    

    Read a Shipping Method

    Reading a shipping method programmatically typically involves retrieving the settings and options for that method.

    You can access these settings using the WooCommerce settings API.

    Update a Shipping Method

    To update a shipping method, you can modify the settings and options associated with that method using the WooCommerce settings API.

    This often involves updating the settings stored in the database.

    Delete a Shipping Method

    Removing a shipping method is infrequently done, as WooCommerce’s core shipping methods are usually not delectable.

    Alternatively, you can disable a shipping method by configuring its settings or choosing not to utilize it.”

    Creating custom shipping methods and conducting CRUD operations on them is a complex process that must be tailored to your unique needs and desired logic.

    The provided code serves as a foundational example and may require further customization to align with your specific requirements.

    Remember to customize the code according to your specific customer data and requirements.

    Ensure that you have the necessary permissions to perform these actions within your WordPress environment.

    Support

    For any technical assistance, please reach us by mail at [email protected]. Kindly visit the WooCommerce Plugins page to see the complete list of our plugins.

    . . .

    Leave a Comment

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


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home