How To Add Product In Woocommerce With Php Code

How to Add Products to WooCommerce with PHP Code: A Beginner-Friendly Guide

WooCommerce is a powerful e-commerce platform built on WordPress, making it easy to set up and manage an online store. While the WooCommerce interface is generally user-friendly, sometimes you need more control or automation. This is where adding products programmatically using PHP code comes in handy. This guide is designed for beginners, walking you through the process step-by-step with real-life examples.

Why would you want to add products using code? Imagine you’re migrating a large product catalog from another platform, or you need to regularly update product information based on an external data source like a supplier’s API. Manually entering hundreds or thousands of products is tedious and error-prone. PHP code allows you to automate this process, saving you time and ensuring accuracy.

Prerequisites

Before we dive in, make sure you have the following:

    • A working WordPress website with WooCommerce installed and activated.
    • Basic knowledge of PHP. You don’t need to be an expert, but understanding variables, arrays, and functions is helpful.
    • Access to your WordPress theme’s `functions.php` file or a custom plugin. Warning: Editing theme files directly is generally discouraged for long-term maintenance. Creating a custom plugin is the recommended approach.

    The Core: `wc_insert_product()`

    The heart of adding products programmatically in WooCommerce is the `wc_insert_product()` function. This function is part of the WooCommerce API and handles the creation of new products. Let’s look at a simple example:

    <?php
    

    function add_simple_product() {

    $product_data = array(

    ‘post_title’ => ‘My Awesome Product’,

    ‘post_content’ => ‘This is a description of my awesome product.’,

    ‘post_status’ => ‘publish’, // Or ‘draft’ if you want to save as a draft

    ‘post_type’ => ‘product’,

    );

    $product_id = wc_insert_product( $product_data );

    if ( is_wp_error( $product_id ) ) {

    error_log( ‘Error creating product: ‘ . $product_id->get_error_message() );

    } else {

    // Product created successfully!

    update_post_meta( $product_id, ‘_regular_price’, ‘19.99’ ); // Set the regular price

    update_post_meta( $product_id, ‘_price’, ‘19.99’ ); // Set the sale price (optional)

    }

    }

    // Call the function to add the product. Important: Only call this function ONCE.

    // add_simple_product();

    ?>

    Explanation:

    • `$product_data`: This array holds the basic information about the product.
    • `post_title`: The name of the product.
    • `post_content`: The product description.
    • `post_status`: Whether the product is published or in draft.
    • `post_type`: Specifies that we are creating a product.
    • `wc_insert_product( $product_data )`: This function creates the product based on the data provided and returns the product ID.
    • `is_wp_error( $product_id )`: Checks if there was an error during product creation.
    • `update_post_meta()`: This function is crucial for setting product properties like price. WooCommerce uses custom fields (post meta) to store this information.
    • `_regular_price`: The normal price of the product.
    • `_price`: The sale price (if the product is on sale). If you don’t set this, it defaults to the `_regular_price`.

    Important Considerations:

    • Call the function only once: The line `// add_simple_product();` is commented out. Uncomment it to run the code and create the product. Then, comment it out again. If you don’t, you’ll create a new product every time the page loads!
    • Error Handling: The `is_wp_error()` check is important. It allows you to catch potential errors and log them for debugging.
    • Product Status: Setting `post_status` to `’publish’` makes the product immediately visible on your store. Use `’draft’` to save it as a draft for review.

    Adding More Product Details

    The previous example only sets the title, description, and price. Here’s how to add more details:

    • Product Image:
    $image_url = 'URL_TO_YOUR_IMAGE'; // Replace with the actual URL
    $upload_dir = wp_upload_dir();
    $image_data = file_get_contents($image_url);
    $filename = basename($image_url);
    

    if (wp_mkdir_p($upload_dir[‘path’])) {

    $file = $upload_dir[‘path’] . ‘/’ . $filename;

    } else {

    $file = $upload_dir[‘basedir’] . ‘/’ . $filename;

    }

    file_put_contents($file, $image_data);

    $wp_filetype = wp_check_filetype($filename, null );

    $attachment = array(

    ‘post_mime_type’ => $wp_filetype[‘type’],

    ‘post_title’ => sanitize_file_name($filename),

    ‘post_content’ => ”,

    ‘post_status’ => ‘inherit’

    );

    $attach_id = wp_insert_attachment( $attachment, $file, $product_id );

    require_once( ABSPATH . ‘wp-admin/includes/image.php’ );

    $attach_data = wp_generate_attachment_metadata( $attach_id, $file );

    wp_update_attachment_metadata( $attach_id, $attach_data );

    set_post_thumbnail( $product_id, $attach_id );

    Explanation: This code downloads the image from the provided URL, saves it to the WordPress uploads directory, creates an attachment post, and sets it as the product’s featured image. Replace `URL_TO_YOUR_IMAGE` with the actual URL of the image.

    • Product Categories:
    wp_set_object_terms( $product_id, array( 'category-slug-1', 'category-slug-2' ), 'product_cat' );
    

    Explanation: Replace `’category-slug-1’` and `’category-slug-2’` with the *slugs* of the product categories you want to assign the product to. You can find the category slugs in the WordPress admin panel under Products -> Categories.

    • Product Tags:
    wp_set_object_terms( $product_id, array( 'tag-slug-1', 'tag-slug-2' ), 'product_tag' );
    

    Explanation: Similar to categories, replace `’tag-slug-1’` and `’tag-slug-2’` with the slugs of the product tags.

    • Product Attributes:
    $attributes = array(
    array(
    'name'         => 'Size', // Attribute name
    'value'        => 'Large, Medium, Small', // Attribute values (comma-separated)
    'is_visible'   => 1, // Visible on the product page
    'is_variation' => 0, // Used for variations?
    'is_taxonomy'  => 0  // Is this a taxonomy attribute? (e.g., color)
    ),
    array(
    'name'         => 'Color',
    'value'        => 'Red, Blue, Green',
    'is_visible'   => 1,
    'is_variation' => 0,
    'is_taxonomy'  => 0
    )
    );
    

    update_post_meta( $product_id, ‘_product_attributes’, $attributes );

    Explanation: This example adds “Size” and “Color” attributes to the product. `is_taxonomy` is set to `0` because these are custom attributes. If you want to use existing WooCommerce taxonomy attributes (like “pa_color” for color), set `is_taxonomy` to `1` and use the taxonomy name in the ‘name’ field.

    Working with Variable Products

    Variable products (products with different options like size and color) are a bit more complex. Here’s a simplified overview:

    1. Create the product as a variable product:

    $product_data['product-type'] = 'variable'; // Add this to the $product_data array
    

    2. Set up attributes: You need to define the attributes that will be used for variations. The code above for adding attributes works. Crucially, set `is_variation` to `1` for the attributes you want to use for variations.

    3. Create variations: Each variation is a separate product linked to the parent variable product. You’ll need to create a new product for each variation, setting the appropriate attribute values and price.

    // Example: Create a large red variation
    $variation_data = array(
    'post_title'  => 'My Awesome Product 
  • Large Red', 'post_content' => '', 'post_status' => 'publish', 'post_parent' => $product_id, // Link to the parent variable product 'post_type' => 'product_variation' );
  • $variation_id = wc_insert_product( $variation_data );

    // Set variation attributes

    update_post_meta( $variation_id, ‘attribute_pa_color’, ‘red’ ); // Assuming ‘pa_color’ is the color attribute taxonomy

    update_post_meta( $variation_id, ‘attribute_size’, ‘large’ ); // Assuming ‘size’ is a custom attribute

    // Set variation price

    update_post_meta( $variation_id, ‘_regular_price’, ‘24.99’ );

    update_post_meta( $variation_id, ‘_price’, ‘24.99’ );

    Important: You’ll need to repeat this process for each variation. The attribute names in `update_post_meta` must match the attribute names used when creating the product attributes. If it’s a taxonomy attribute like color, use the `attribute_pa_color` format.

    Putting it All Together: A More Complete Example

    <?php
    

    function add_complete_product() {

    $product_data = array(

    ‘post_title’ => ‘Deluxe Widget’,

    ‘post_content’ => ‘A premium widget designed for maximum performance.’,

    ‘post_status’ => ‘publish’,

    ‘post_type’ => ‘product’,

    );

    $product_id = wc_insert_product( $product_data );

    if ( is_wp_error( $product_id ) ) {

    error_log( ‘Error creating product: ‘ . $product_id->get_error_message() );

    return; // Exit the function if there’s an error

    }

    // Set price

    update_post_meta( $product_id, ‘_regular_price’, ‘49.99’ );

    update_post_meta( $product_id, ‘_price’, ‘49.99’ );

    // Set featured image (replace with your image URL)

    $image_url = ‘https://example.com/widget.jpg’; // REPLACE THIS WITH YOUR IMAGE URL!

    if(filter_var($image_url, FILTER_VALIDATE_URL)){

    $upload_dir = wp_upload_dir();

    $image_data = file_get_contents($image_url);

    if($image_data){

    $filename = basename($image_url);

    if (wp_mkdir_p($upload_dir[‘path’])) {

    $file = $upload_dir[‘path’] . ‘/’ . $filename;

    } else {

    $file = $upload_dir[‘basedir’] . ‘/’ . $filename;

    }

    $put_contents = file_put_contents($file, $image_data);

    if($put_contents > 0){

    $wp_filetype = wp_check_filetype($filename, null );

    $attachment = array(

    ‘post_mime_type’ => $wp_filetype[‘type’],

    ‘post_title’ => sanitize_file_name($filename),

    ‘post_content’ => ”,

    ‘post_status’ => ‘inherit’

    );

    $attach_id = wp_insert_attachment( $attachment, $file, $product_id );

    require_once( ABSPATH . ‘wp-admin/includes/image.php’ );

    $attach_data = wp_generate_attachment_metadata( $attach_id, $file );

    wp_update_attachment_metadata( $attach_id, $attach_data );

    set_post_thumbnail( $product_id, $attach_id );

    } else{

    error_log(‘Error saving image.’);

    }

    } else {

    error_log(‘Error getting image content from url.’);

    }

    } else {

    error_log(‘Invalid image url provided.’);

    }

    // Set category (replace with your category slug)

    wp_set_object_terms( $product_id, array( ‘widgets’ ), ‘product_cat’ ); // Replace ‘widgets’ with your category slug

    // Set tags (replace with your tag slugs)

    wp_set_object_terms( $product_id, array( ‘premium’, ‘widget’ ), ‘product_tag’ ); // Replace with your tag slugs

    // Set attributes

    $attributes = array(

    array(

    ‘name’ => ‘Material’,

    ‘value’ => ‘Aluminum, Stainless Steel’,

    ‘is_visible’ => 1,

    ‘is_variation’ => 0,

    ‘is_taxonomy’ => 0

    )

    );

    update_post_meta( $product_id, ‘_product_attributes’, $attributes );

    }

    //Uncomment to run once then comment again.

    //add_complete_product();

    ?>

    Remember to replace the placeholder URLs and slugs with your actual data.

    Best Practices and SEO Considerations

    • Use Descriptive Titles and Descriptions: Just like with manually added products, use clear and compelling titles and descriptions that include relevant keywords. This helps with search engine optimization (SEO).
    • Optimize Images: Make sure your product images are properly sized and optimized for the web. Use descriptive alt text for images to improve SEO and accessibility.
    • Use Relevant Categories and Tags: Categorize and tag your products appropriately to help customers find them easily and improve SEO.
    • Consider using a Plugin: If you need to import large product catalogs regularly, consider using a dedicated WooCommerce import plugin. These plugins often provide more advanced features and error handling. Look for plugins with good reviews and active support.
    • Test Thoroughly: After adding products programmatically, always check the product pages on your webs

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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