• Resolved Sivustonikkari

    (@risalmin)


    A WordPress site with only Woocommerce and my custom plugin, using a barebone theme with empty functions.php. WordPress and Woocommerce on latest versions.
    I create a product like this:
    $product_name = “PRODUCT NAME”;
    $product = new \WC_Product_Simple();
    $product->set_name( $product_name );
    $product->set_sku( $product_sku );
    … //etc
    The slug (post_name) for the product is the same as post_title (PRODUCT NAME) and not product-name as it should.

    What could be the possible reason for this?!? I am creating about 9000 products in a loop.

Viewing 1 replies (of 1 total)
  • By default, WooCommerce automatically generates the slug based on the product name (post_title) when a product is saved or updated. However, when creating products programmatically in a loop, the slug generation process might not be triggered automatically.

    To ensure that the slugs are generated correctly for your products, you can manually update the slugs using the wp_update_post() function after creating each product. Here’s an example of how you can modify your code to include the slug update:

    $product_name = 'PRODUCT NAME';
    $product = new \WC_Product_Simple();
    $product->set_name($product_name);
    $product->set_sku($product_sku);
    // ... additional product setup code ...
    
    // Save the product
    $product_id = $product->save();
    
    // Generate the slug for the product
    $slug = sanitize_title($product_name);
    
    // Update the product post with the generated slug
    wp_update_post(array(
      'ID' => $product_id,
      'post_name' => $slug,
    ));
    

    In the code above, after creating each product using $product->save(), we generate the slug using sanitize_title() based on the product name. Then, we use wp_update_post() to update the product post with the generated slug.

    By including these additional steps in your loop, you should be able to ensure that the slugs are generated correctly for each product you create programmatically.

    Thanks
    Ahir Hemant

Viewing 1 replies (of 1 total)
  • The topic ‘slug is not sanitized when creating a product programatically’ is closed to new replies.