WooCommerce: Produkt nach Code erstellen

Lesezeit: 12 Minuten

Benutzeravatar von Beer Brother
Bier Bruder

Mein Geschäft verkauft Vinyl-Aufkleber. Jedes Produkt (Aufkleber) hat 144 Variationen (24 Farben, 3 Größen und 2 Ausrichtungen). Jeder Variante muss eine eindeutige SKU zugewiesen werden.

Katalog manuell füllen ist unrealistisch. Ich werde ein Formular erstellen, in dem der Benutzer den Namen, die Beschreibung und das Hauptbild des Produkts sowie die möglichen Größen und Farben angibt. Bei der Verarbeitung des Formulars muss ich ein Produkt und alle seine Variationen erstellen.

Wie erstelle ich ein Produkt und seine Variationen?

  • Müssen Sie ein Bild erstellen oder nur mögliche Optionen ausdrucken?

    – Peon

    16. Juli 2012 um 11:50 Uhr

  • Jetzt gibt es eine V2-REST-API, ich würde empfehlen, diese zum Erstellen von Produkten zu verwenden. Die API kann sich als anderer Benutzer anmelden und berücksichtigt alle Feinheiten, die beim manuellen Erstellen eines Produkts möglicherweise übersehen werden. Es geht auch darum, eine einzelne große Datenstruktur zusammenzustellen und sie in einer Aktion zur Einrichtung zu versenden.

    – Jason

    28. Februar 2015 um 23:41 Uhr

  • WooCommerce hat in 3.0 neue CRUD-Objekte eingeführt – es wird dringend empfohlen, diese zu verwenden, anstatt reine WordPress-Funktionen zu verwenden, um rückentwickelte Daten zu aktualisieren. github.com/woocommerce/woocommerce/wiki/CRUD-Objects-in-3.0

    – Pavel Lishin

    29. April 2019 um 18:09 Uhr

Benutzeravatar von Avant Garde
Avantgarde

Ich hatte eine ähnliche Situation, hier ist, was ich herausgefunden habe.

Produkte sind eigentlich a benutzerdefinierter Beitragstyp (ganz offensichtlich! :P), damit Sie verwenden können wp_insert_post um ein neues Produkt einzufügen. Nach dem Einfügen erhalten Sie die ID des neuen Produktbeitragstyps use update_post_meta um einen Metaschlüssel und einen Metawert als festzulegen _visibility und visible beziehungsweise. Wenn Sie die Sichtbarkeit nicht einstellen, wird Ihr neu hinzugefügtes Produkt niemals in Ihrem Shop sichtbar sein. Alternativ können Sie die Sichtbarkeit auch vom Backend aus einstellen. Verwenden Sie für die verschiedenen Größen des Produkts Variationen dieses Produkts. Sie können für jede Variante einen anderen Typ, Preis, SKU usw. festlegen. All dies sind Post-Meta, daher können Sie PHP-Code verwenden, um die Variationen und das Zeug hinzuzufügen. Studiere die postmeta Tabelle, um die Schlüsselnamen anzuzeigen.

  • wenn ich setze update_post_meta( $new_product_post_id, '_visibility', 'hidden' ); aber auf der Produktdetailseite im Backend. Es zeigt immer noch sichtbar Wert. was falsch?

    – huykon225

    12. Juni 2017 um 2:36 Uhr

Benutzeravatar von Vedran Šego
Vedran Šego

Wie Jason in seinem Kommentar schrieb, ist die REST-API hier der richtige Weg. Dies kann auch ohne HTTP-REST-Anforderungen erfolgen, sodass es auch auf WordPress-Installationen funktioniert, deren REST-Schnittstelle deaktiviert ist.

Hier ist eine einfache Funktion, die ich zu diesem Zweck erstellt habe:

$products_controler = new WC_REST_Products_Controller();
function create_item($rest_request) {
    global $products_controler;
    if (!isset($rest_request['status']))
        $rest_request['status'] = 'publish';
    $wp_rest_request = new WP_REST_Request('POST');
    $wp_rest_request->set_body_params($rest_request);
    return $products_controler->create_item($wp_rest_request);
}

Hier, $rest_request ist ein Array, das Sie normalerweise über REST senden würden (siehe die docs hier).

Das $products_controler Die Variable ist global, da ich diese Funktion mehrmals aufrufen musste und das Objekt nicht jedes Mal neu erstellen wollte. Fühlen Sie sich frei, es lokal zu machen.

Dies funktioniert für alle Arten von Produkten (einfach, gruppiert, variabel, …) und sollte widerstandsfähiger gegen interne Änderungen von WooCommerce sein, als die Produkte manuell hinzuzufügen wp_insert_post und update_post_meta.

Bearbeiten: Da diese Antwort immer noch gelegentlich positive Stimmen erhält, ist hier eine WooCommerce 3.0+ aktualisieren. Die Änderung besteht darin, dass die Variationen nicht mehr automatisch hinzugefügt werden, sodass wir dies selbst tun müssen.

Dies ist die aktuelle Version der Funktion:

protected function create_item( $rest_request ) {
    if ( ! isset( $rest_request['status'] ) ) {
        $rest_request['status'] = $this->plugin->get_option( 'default_published_status' );
    }
    if ( ! isset( $this->products_controler ) ) {
        $this->products_controler = new WC_REST_Products_Controller();
    }
    $wp_rest_request = new WP_REST_Request( 'POST' );
    $wp_rest_request->set_body_params( $rest_request );
    $res = $this->products_controler->create_item( $wp_rest_request );
    $res = $res->data;
    // The created product must have variations
    // If it doesn't, it's the new WC3+ API which forces us to build those manually
    if ( ! isset( $res['variations'] ) )
        $res['variations'] = array();
    if ( count( $res['variations'] ) == 0 && count( $rest_request['variations'] ) > 0 ) {
        if ( ! isset( $this->variations_controler ) ) {
            $this->variations_controler = new WC_REST_Product_Variations_Controller();
        }
        foreach ( $rest_request['variations'] as $variation ) {
            $wp_rest_request = new WP_REST_Request( 'POST' );
            $variation_rest = array(
                'product_id' => $res['id'],
                'regular_price' => $variation['regular_price'],
                'image' => array( 'id' => $variation['image'][0]['id'], ),
                'attributes' => $variation['attributes'],
            );
            $wp_rest_request->set_body_params( $variation_rest );
            $new_variation = $this->variations_controler->create_item( $wp_rest_request );
            $res['variations'][] = $new_variation->data;
        }
    }
    return $res;
}

Dies wird in verwendet Drachendruck und Dropshipping auf Anfrage plugin, ab der (demnächst erscheinenden) Version 1.1, in file api/publish_products.php.

Es gibt auch eine viel längere “schnelle” Version namens create_products_fast die direkt in die Datenbank schreibt, wodurch sie möglicherweise weniger robust gegenüber zukünftigen WP/WC-Änderungen ist, aber viel schneller ist (wenige Sekunden gegenüber wenigen Minuten für unsere 34-Produktpalette auf meinem Testcomputer).

  • Hallo, die Version create_products_fast ist Teil des WC oder wird im Kite Print Plugin verwendet?

    – Jeans K. Real

    23. November 2017 um 13:48 Uhr

  • @JeansK.Real Es ist eine Funktion im (inzwischen eingestellten) Plugin von Kite, in der alle SQL-Anforderungen, die normalerweise über viele WP-Funktionen (in unserem Fall einige hundert Aufrufe) ausgeführt werden, in nur 5 oder 6 Bulk-SQL-Aufrufen gruppiert wurden Es ist blitzschnell, aber auch nicht sehr widerstandsfähig gegenüber WP / WC-Änderungen. Als Backup für solche Fälle hatten wir eine Einstellung, die das Feature ein- oder ausschaltet (im letzteren Fall wurde stattdessen die obige Funktion verwendet).

    – Vedran Šego

    24. November 2017 um 12:36 Uhr

Dies ist der logischste und einfachste Weg. Einfaches Produkt verwenden Sie den folgenden Code:

$objProduct = new WC_Product();

und für die variable Produktverwendung unter der Codezeile.

$objProduct = new WC_Product_Variable();

Der nächste Schritt besteht darin, die Meta-Eigenschaften wie Name, Preis usw. und Variantendaten (im Falle eines variablen Produkts) festzulegen.

$objProduct->set_name("Product Title");
$objProduct->set_status("publish");  // can be publish,draft or any wordpress post status
$objProduct->set_catalog_visibility('visible'); // add the product visibility status
$objProduct->set_description("Product Description");
$objProduct->set_sku("product-sku"); //can be blank in case you don't have sku, but You can't add duplicate sku's
$objProduct->set_price(10.55); // set product price
$objProduct->set_regular_price(10.55); // set product regular price
$objProduct->set_manage_stock(true); // true or false
$objProduct->set_stock_quantity(10);
$objProduct->set_stock_status('instock'); // in stock or out of stock value
$objProduct->set_backorders('no');
$objProduct->set_reviews_allowed(true);
$objProduct->set_sold_individually(false);
$objProduct->set_category_ids(array(1,2,3)); // array of category ids, You can get category id from WooCommerce Product Category Section of WordPress Admin

Der folgende Code wird verwendet, wenn Sie Produktbilder hochladen möchten

function uploadMedia($image_url){
    require_once('wp-admin/includes/image.php');
    require_once('wp-admin/includes/file.php');
    require_once('wp-admin/includes/media.php');
    $media = media_sideload_image($image_url,0);
    $attachments = get_posts(array(
        'post_type' => 'attachment',
        'post_status' => null,
        'post_parent' => 0,
        'orderby' => 'post_date',
        'order' => 'DESC'
    ));
    return $attachments[0]->ID;
}
// above function uploadMedia, I have written which takes an image url as an argument and upload image to wordpress and returns the media id, later we will use this id to assign the image to product.
$productImagesIDs = array(); // define an array to store the media ids.
$images = array("image1 url","image2 url","image3 url"); // images url array of product
foreach($images as $image){
    $mediaID = uploadMedia($image); // calling the uploadMedia function and passing image url to get the uploaded media id
    if($mediaID) $productImagesIDs[] = $mediaID; // storing media ids in a array.
}
if($productImagesIDs){
    $objProduct->set_image_id($productImagesIDs[0]); // set the first image as primary image of the product

        //in case we have more than 1 image, then add them to product gallery. 
    if(count($productImagesIDs) > 1){
        $objProduct->set_gallery_image_ids($productImagesIDs);
    }
}

Speichern Sie das Produkt, um die WooCommerce-Produkt-ID zu erhalten

$product_id = $objProduct->save(); // it will save the product and return the generated product id

Hinweis: Für ein einfaches Produkt sind die obigen Schritte ausreichend, die folgenden Schritte gelten für variable Produkte oder Produkte mit Attributen.

Der folgende Code wird verwendet, um Produktattribute hinzuzufügen.

$attributes = array(
    array("name"=>"Size","options"=>array("S","L","XL","XXL"),"position"=>1,"visible"=>1,"variation"=>1),
    array("name"=>"Color","options"=>array("Red","Blue","Black","White"),"position"=>2,"visible"=>1,"variation"=>1)
);
if($attributes){
    $productAttributes=array();
    foreach($attributes as $attribute){
        $attr = wc_sanitize_taxonomy_name(stripslashes($attribute["name"])); // remove any unwanted chars and return the valid string for taxonomy name
        $attr="pa_".$attr; // woocommerce prepend pa_ to each attribute name
        if($attribute["options"]){
            foreach($attribute["options"] as $option){
                wp_set_object_terms($product_id,$option,$attr,true); // save the possible option value for the attribute which will be used for variation later
            }
        }
        $productAttributes[sanitize_title($attr)] = array(
            'name' => sanitize_title($attr),
            'value' => $attribute["options"],
            'position' => $attribute["position"],
            'is_visible' => $attribute["visible"],
            'is_variation' => $attribute["variation"],
            'is_taxonomy' => '1'
        );
    }
    update_post_meta($product_id,'_product_attributes',$productAttributes); // save the meta entry for product attributes
}

Der folgende Code wird verwendet, um Produktvarianten hinzuzufügen.

$variations = array(
    array("regular_price"=>10.11,"price"=>10.11,"sku"=>"ABC1","attributes"=>array(array("name"=>"Size","option"=>"L"),array("name"=>"Color","option"=>"Red")),"manage_stock"=>1,"stock_quantity"=>10),
    array("regular_price"=>10.11,"price"=>10.11,"sku"=>"ABC2","attributes"=>array(array("name"=>"Size","option"=>"XL"),array("name"=>"Color","option"=>"Red")),"manage_stock"=>1,"stock_quantity"=>10)
    
);
if($variations){
    try{
        foreach($variations as $variation){
            $objVariation = new WC_Product_Variation();
            $objVariation->set_price($variation["price"]);
            $objVariation->set_regular_price($variation["regular_price"]);
            $objVariation->set_parent_id($product_id);
            if(isset($variation["sku"]) && $variation["sku"]){
                $objVariation->set_sku($variation["sku"]);
            }
            $objVariation->set_manage_stock($variation["manage_stock"]);
            $objVariation->set_stock_quantity($variation["stock_quantity"]);
            $objVariation->set_stock_status('instock'); // in stock or out of stock value
            $var_attributes = array();
            foreach($variation["attributes"] as $vattribute){
                $taxonomy = "pa_".wc_sanitize_taxonomy_name(stripslashes($vattribute["name"])); // name of variant attribute should be same as the name used for creating product attributes
                $attr_val_slug =  wc_sanitize_taxonomy_name(stripslashes($vattribute["option"]));
                $var_attributes[$taxonomy]=$attr_val_slug;
            }
            $objVariation->set_attributes($var_attributes);
            $objVariation->save();
        }
    }
    catch(Exception $e){
        // handle exception here
    }
}

Das ist es Der obige Code reicht aus, um ein einfaches oder variables WooCommerce-Produkt mit Bildern, Attributen und Varianten hinzuzufügen.

Benutzeravatar von Sophivorus
Sophivorus

Basierend auf Vedrans Antwort ist hier der minimale Code zum Posten eines WooCommerce-Produkts über PHP:

$data = [
    'name' => 'Test product',
    'description' => 'Lorem ipsum',
];
$request = new WP_REST_Request( 'POST' );
$request->set_body_params( $data );
$products_controller = new WC_REST_Products_Controller;
$response = $products_controller->create_item( $request );

herrs Benutzeravatar
Herr

Bitte beziehen Sie sich auf woocommerce-mit-php-codewo der vollständige Code angegeben ist.

Wie Avant Garde sagte, werden Produkte in der Post hinzugefügt mit:

post_type = "product"

vijays Benutzeravatar
Vijay

Ich benutze diesen Code:

$sku = 21333;
$size="S";
$stock = 2;
$price_a = 60;
$price_b = 30;

$product_parent = get_product_by_sku($sku);
$product = new WC_Product_Variable($product_parent->id);
$variations = $product->get_available_variations();

// First off all delete all variations
foreach($variations as $prod_variation) {
  $metaid=mysql_query("SELECT meta_id FROM wp_postmeta WHERE post_id = ".$prod_variation['variation_id']);
  while ($row = mysql_fetch_assoc($metaid)) {
    mysql_query("DELETE FROM wp_postmeta WHERE meta_id = ".$row['meta_id']);
  }
  mysql_query("DELETE FROM wp_posts WHERE ID = ".$prod_variation['variation_id']);
}

// Now add new variation
$thevariation = array(
  'post_title'=> '',
  'post_name' => 'product-' . $product_parent->id . '-variation',
  'post_status' => 'publish',
  'post_parent' => $product_parent->id,
  'post_type' => 'product_variation',
  'guid'=>home_url() . '/?product_variation=product-' . $product_parent->id . '-variation'
);
$variation_id = wp_insert_post( $thevariation );
update_post_meta($variation_id, 'post_title', 'Variation #' . $variation_id . ' of '. $product_parent->id);

wp_set_object_terms( $variation_id, $size, 'pa_size' );
update_post_meta($variation_id, 'attribute_pa_size', $size);

update_post_meta($variation_id, '_regular_price', $price_a);
update_post_meta($variation_id, '_downloadable_files', '');
update_post_meta($variation_id, '_download_expiry', '');
update_post_meta($variation_id, '_download_limit', '');
update_post_meta($variation_id, '_sale_price_dates_to', '');
update_post_meta($variation_id, '_sale_price_dates_from', '');
update_post_meta($variation_id, '_backorders', 'no');
update_post_meta($variation_id, '_stock_status', 'instock');
update_post_meta($variation_id, '_height', '');
update_post_meta($variation_id, '_manage_stock', 'yes');
update_post_meta($variation_id, '_width', '');
update_post_meta($variation_id, '_sale_price_dates_from', '');
update_post_meta($variation_id, '_backorders', 'no');
update_post_meta($variation_id, '_stock_status', 'instock');
update_post_meta($variation_id, '_manage_stock', 'yes');
update_post_meta($variation_id, '_height', '');
update_post_meta($variation_id, '_width', '');
update_post_meta($variation_id, '_length', '');
update_post_meta($variation_id, '_weight', '');
update_post_meta($variation_id, '_downloadable', 'no');
update_post_meta($variation_id, '_virtual', 'no');
update_post_meta($variation_id, '_thumbnail_id', '0');
update_post_meta($variation_id, '_sku', '');

update_post_meta($variation_id, '_sale_price', $price_b);
update_post_meta($variation_id, '_price', $price_b);
update_post_meta($product_parent->id, '_min_variation_price', $price_b);
update_post_meta($product_parent->id, '_max_variation_price', $price_b);
update_post_meta($product_parent->id, '_min_price_variation_id', $variation_id);
update_post_meta($product_parent->id, '_max_price_variation_id', $variation_id);
update_post_meta($product_parent->id, '_min_variation_regular_price', $price_a);
update_post_meta($product_parent->id, '_max_variation_regular_price', $price_a);
update_post_meta($product_parent->id, '_min_regular_price_variation_id', $variation_id);
update_post_meta($product_parent->id, '_max_regular_price_variation_id', $variation_id);
update_post_meta($product_parent->id, '_min_variation_sale_price', $price_b);
update_post_meta($product_parent->id, '_max_variation_sale_price', $price_b);
update_post_meta($product_parent->id, '_min_sale_price_variation_id', $variation_id);
update_post_meta($product_parent->id, '_max_sale_price_variation_id', $variation_id);
update_post_meta($product_parent->id, '_price', $price_b);

update_post_meta( $variation_id, '_stock', $stock );
update_post_meta($product_parent->id, 'post_status', 'publish');

1402320cookie-checkWooCommerce: Produkt nach Code erstellen

This website is using cookies to improve the user-friendliness. You agree by using the website further.

Privacy policy