demo-product-publisher.php

WooCommerce Demo Product Publisher

This file contains a WordPress function that automatically publishes a 'Demo' product to a WooCommerce shop upon initialization. It includes product details and ensures no duplicates by checking for an existing SKU.

<?php function cwpai_publish_demo_product() { $product_name = 'Demo'; $product_args = array( 'name' => $product_name, 'type' => 'simple', 'regular_price' => '100', 'description' => 'This is a demo product.', 'short_description' => 'A simple demo product.', 'status' => 'publish', ); $existing_product_id = wc_get_product_id_by_sku('demo-product'); if ( $existing_product_id ) { return; // Product already exists, no action needed. } $product = new WC_Product_Simple(); foreach ($product_args as $key => $value) { $method = 'set_' . $key; if (method_exists($product, $method)) { $product->$method($value); } } $product->set_sku('demo-product'); // Ensure uniqueness. $product_id = $product->save(); if ( $product_id ) { // Product successfully created. } } add_action('init', 'cwpai_publish_demo_product');

Frequently Asked Questions

The code automatically creates a simple WooCommerce product named 'Demo' when WordPress initializes.

Related public snippets