Prestashop : créer un produit en PHP

Ce bout de code est à la base inclus dans une boucle qui créée plusieurs produits. Je stocke les données des produits dans des tableaux (ou dans un fichier csv), je met toutes les images dans un dossier de manière à pouvoir y accéder avec le script et je les créé tous à la volée.

La boucle initiale devait créer tout le catalogue. Il y avait donc un tableau de catégories puis chaque produit était intégré à la catégorie à l’aide de son ID (plutôt que d’utiliser l’ID 2 comme ici).

<?php

    require('config/config.inc.php');

// langue par défaut de la boutique
    $default_lang = Configuration::get('PS_LANG_DEFAULT');

// id de la catégorie par défaut du produit
    $category_id = 2;

// caractéristiques du produit
    $product_name = "Nom du produit";
    $product_description = "Desription du produit";
    $product_description_short = "Desription courte du produit";

// début de l'ajout
    $product = new Product();
    $product->name = array((int)$default_lang => $product_name);
    $product->id_category = $category_id;
    $product->id_category_default = $category_id;
    $product->price = (int)50;
    $product->link_rewrite = array((int)$default_lang => Tools::link_rewrite($product_name));

    $product->description = array($default_lang => $product_description);
    $product->description_short = array($default_lang => $product_description_short);

    $product->quantity = 100;
    $product->add();

// je définie la quantité du produit
    StockAvailable::setQuantity((int)$product->id, 0, (int)$product->quantity, Context::getContext()->shop->id);

// j'ajoute des mots clés au produit
    Tag::addTags((int)$default_lang, (int)$product->id, "mots clés");

    $product->addToCategories(array($category_id));

// ajout de l'image
    $image = new Image();
    $image->id_product = $product->id;
    $image->position = Image::getHighestPosition($product->id) + 1;
    $image->cover = true;
    $image->add();

    copyImg((int)$product->id, (int)$image->id, 'https://www.google.com/logos/doodles/2014/first-day-of-school-2014-5475863151771648-hp.jpg', 'products', true);

    /* fonctions issues du core */

    function copyImg($id_entity, $id_image = null, $url, $entity = 'products', $regenerate = true)
    {
        $tmpfile = tempnam(_PS_TMP_IMG_DIR_, 'ps_import');
        $watermark_types = explode(',', Configuration::get('WATERMARK_TYPES'));

        switch ($entity) {
            default:
            case 'products':
                $image_obj = new Image($id_image);
                $path = $image_obj->getPathForCreation();
                break;
            case 'categories':
                $path = _PS_CAT_IMG_DIR_ . (int)$id_entity;
                break;
            case 'manufacturers':
                $path = _PS_MANU_IMG_DIR_ . (int)$id_entity;
                break;
            case 'suppliers':
                $path = _PS_SUPP_IMG_DIR_ . (int)$id_entity;
                break;
        }

        $url = urldecode(trim($url));
        $parced_url = parse_url($url);

        if (isset($parced_url['path'])) {
            $uri = ltrim($parced_url['path'], '/');
            $parts = explode('/', $uri);
            foreach ($parts as &$part) {
                $part = rawurlencode($part);
            }
            unset($part);
            $parced_url['path'] = '/' . implode('/', $parts);
        }

        if (isset($parced_url['query'])) {
            $query_parts = array();
            parse_str($parced_url['query'], $query_parts);
            $parced_url['query'] = http_build_query($query_parts);
        }

        if (!function_exists('http_build_url')) {
            require_once(_PS_TOOL_DIR_ . 'http_build_url/http_build_url.php');
        }

        $url = http_build_url('', $parced_url);

        $orig_tmpfile = $tmpfile;

        if (Tools::copy($url, $tmpfile)) {
// Evaluate the memory required to resize the image: if it's too much, you can't resize it.
            if (!ImageManager::checkImageMemoryLimit($tmpfile)) {
                @unlink($tmpfile);
                return false;
            }

            $tgt_width = $tgt_height = 0;
            $src_width = $src_height = 0;
            $error = 0;
            ImageManager::resize($tmpfile, $path . '.jpg', null, null, 'jpg', false, $error, $tgt_width, $tgt_height, 5,
                $src_width, $src_height);
            $images_types = ImageType::getImagesTypes($entity, true);

            if ($regenerate) {
                $previous_path = null;
                $path_infos = array();
                $path_infos[] = array($tgt_width, $tgt_height, $path . '.jpg');
                foreach ($images_types as $image_type) {
                    $tmpfile = get_best_path($image_type['width'], $image_type['height'], $path_infos);

                    if (ImageManager::resize($tmpfile, $path . '-' . stripslashes($image_type['name']) . '.jpg', $image_type['width'],
                        $image_type['height'], 'jpg', false, $error, $tgt_width, $tgt_height, 5,
                        $src_width, $src_height)) {
// the last image should not be added in the candidate list if it's bigger than the original image
                        if ($tgt_width <= $src_width && $tgt_height <= $src_height) {
                            $path_infos[] = array($tgt_width, $tgt_height, $path . '-' . stripslashes($image_type['name']) . '.jpg');
                        }
                        if ($entity == 'products') {
                            if (is_file(_PS_TMP_IMG_DIR_ . 'product_mini_' . (int)$id_entity . '.jpg')) {
                                unlink(_PS_TMP_IMG_DIR_ . 'product_mini_' . (int)$id_entity . '.jpg');
                            }
                            if (is_file(_PS_TMP_IMG_DIR_ . 'product_mini_' . (int)$id_entity . '_' . (int)Context::getContext()->shop->id . '.jpg')) {
                                unlink(_PS_TMP_IMG_DIR_ . 'product_mini_' . (int)$id_entity . '_' . (int)Context::getContext()->shop->id . '.jpg');
                            }
                        }
                    }
                    if (in_array($image_type['id_image_type'], $watermark_types)) {
                        Hook::exec('actionWatermark', array('id_image' => $id_image, 'id_product' => $id_entity));
                    }
                }
            }
        } else {
            @unlink($orig_tmpfile);
            return false;
        }
        unlink($orig_tmpfile);
        return true;
    }

    function get_best_path($tgt_width, $tgt_height, $path_infos)
    {
        $path_infos = array_reverse($path_infos);
        $path = '';
        foreach ($path_infos as $path_info) {
            list($width, $height, $path) = $path_info;
            if ($width >= $tgt_width && $height >= $tgt_height) {
                return $path;
            }
        }
        return $path;
    }
Prestashop : créer un utilisateur et son adresse en PHP
Exporter les commandes Prestashop en CSV sans module

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *