Jump to content

[Tutorial][PS 1.7+] Adding prestashop products programmatically


Recommended Posts

Compatible with version: Prestashop 1.7+
Tutorial last update: 27/09/2020

A while ago i received the question on how to add products programmatically using a PHP file. After looking around in the Prestashop files and searching the worldwideweb  i have come up with a working script. I decided to share this code with the Prestashop community. If you have any questions our improvements don't hesitate to ask or say them.

The file we are creating can be easily run with a cron-job and is able to fetch data from a page using JSON trough an Ajax call.

Lets get started!

  1. The first step is creating a new PHP file in your admin folder.
    Create a new PHP file in the folder yourstore/back-office/FILENAME.php. In our small tutorial we use the filename importmyproduct.php
     
  2. Setting up connection with he config file
    First we start to check if the global variable _PS_ADMIN_DIR_ is defined. After we check that _PS_ADMIN_DIR_ is defined we will make connection with the prestashop config.inc.php file.
    So on top of our page we will add following code.
    <?php
        // Check if _PS_ADMIN_DIR_ is defined
        if (!defined('_PS_ADMIN_DIR_')) {
            // if _PS_ADMIN_DIR_ is not defined, define.
            define('_PS_ADMIN_DIR_', getcwd());
        }
        // Setup connection with config.inc.php (required for database connection, ...)
        include(_PS_ADMIN_DIR_.'/../config/config.inc.php');

     

  3. Adding access security and check if page is setup correctly.
    Since we do not want that our importmyproduct.php can be easily accessed by strangers we will add a security feature. We will also display our first echo to check if everything is working correctly. After we have setup our secure-key we can visit our PHP page by going to yourstore.com/yourbackoffice/importmyproduct.php?secure_key=yoursecuretoken
        $secure_key = 'ed3fa1ce558e1c2528cfbaa3f99403';
    
        // Check if the client use the correct secure_key, url to use: www.yourstore.com/yourbackoffice/importmyproduct.php?secure_key=ed3fa1ce558e1c2528cfbaa3f99403
        if(!Tools::getValue('secure_key') || Tools::getValue('secure_key') != $secure_key) {
            // If the secure_key is not set our not equal the php page will stop running.
            die('UNAUTHORIZED: We dont want you on this page!');
        }
        echo 'Welcome, the secure_key you have used is correct. Now we can start adding product programmatically ... <br>';
  4. Our product import function
    In this next step we will add our product import function which can be called later on to import a new product.
        function addProduct($ean13, $ref, $name, $qty, $text, $features, $price, $imgUrl, $catDef, $catAll) {
            $product = new Product();              // Create new product in prestashop
            $product->ean13 = $ean13;
            $product->reference = $ref;
            $product->name = createMultiLangField($name);
            $product->description = htmlspecialchars($text);
            $product->id_category_default = $catDef;
            $product->redirect_type = '301';
            $product->price = $price;
            $product->quantity = $qty;
            $product->minimal_quantity = 1;
            $product->show_price = 1;
            $product->on_sale = 0;
            $product->online_only = 0;
            $product->meta_description = '';
            $product->add();                        // Submit new product
            $product->addToCategories($catAll);     // After product is submitted insert all categories
    
            // Insert "feature name" and "feature value"
            if (is_array($features)) {
                foreach ($features as $feature) {
                    $attributeName = $feature['name'];
                    $attributeValue = $feature['value'];
    
                    // 1. Check if 'feature name' exist already in database
                    $FeatureNameId = Db::getInstance()->getValue('SELECT id_feature FROM ' . _DB_PREFIX_ . 'feature_lang WHERE name = "' . pSQL($attributeName) . '"');
                    // If 'feature name' does not exist, insert new.
                    if (empty($getFeatureName)) {
                        Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'feature` (`id_feature`,`position`) VALUES (0, 0)');
                        $FeatureNameId = Db::getInstance()->Insert_ID(); // Get id of "feature name" for insert in product
                        Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'feature_shop` (`id_feature`,`id_shop`) VALUES (' . $FeatureNameId . ', 1)');
                        Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'feature_lang` (`id_feature`,`id_lang`, `name`) VALUES (' . $FeatureNameId . ', ' . Context::getContext()->language->id . ', "' . pSQL($attributeName) . '")');
                    }
    
                    // 1. Check if 'feature value name' exist already in database
                    $FeatureValueId = Db::getInstance()->getValue('SELECT id_feature_value FROM webshop_feature_value WHERE id_feature_value IN (SELECT id_feature_value FROM webshop_feature_value_lang WHERE value = "' . pSQL($attributeValue) . '") AND id_feature = ' . $FeatureNameId);
                    // If 'feature value name' does not exist, insert new.
                    if (empty($FeatureValueId)) {
                        Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'feature_value` (`id_feature_value`,`id_feature`,`custom`) VALUES (0, ' . $FeatureNameId . ', 0)');
                        $FeatureValueId = Db::getInstance()->Insert_ID();
                        Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'feature_value_lang` (`id_feature_value`,`id_lang`,`value`) VALUES (' . $FeatureValueId . ', ' . Context::getContext()->language->id . ', "' . pSQL($attributeValue) . '")');
                    }
                    Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'feature_product` (`id_feature`, `id_product`, `id_feature_value`) VALUES (' . $FeatureNameId . ', ' . $product->id . ', ' . $FeatureValueId . ')');
                }
            }
    
            // add product image.
            $shops = Shop::getShops(true, null, true);
            $image = new Image();
            $image->id_product = $product->id;
            $image->position = Image::getHighestPosition($product->id) + 1;
            $image->cover = true;
            if (($image->validateFields(false, true)) === true && ($image->validateFieldsLang(false, true)) === true && $image->add()) {
                $image->associateTo($shops);
                if (!uploadImage($product->id, $image->id, $imgUrl)) {
                    $image->delete();
                }
            }
            echo 'Product added successfully (ID: ' . $product->id . ')';
        }

     

  5. We also will need a function to handle our image upload, add below following code:
    This function will insert the image into your store and assign it to your created product.
        function uploadImage($id_entity, $id_image = null, $imgUrl) {
            $tmpfile = tempnam(_PS_TMP_IMG_DIR_, 'ps_import');
            $watermark_types = explode(',', Configuration::get('WATERMARK_TYPES'));
            $image_obj = new Image($id_image);
            $path = $image_obj->getPathForCreation();
            $imgUrl = str_replace(' ', '%20', trim($imgUrl));
            // Evaluate the memory required to resize the image: if it's too big we can't resize it.
            if (!ImageManager::checkImageMemoryLimit($imgUrl)) {
                return false;
            }
            if (@copy($imgUrl, $tmpfile)) {
                ImageManager::resize($tmpfile, $path . '.jpg');
                $images_types = ImageType::getImagesTypes('products');
                foreach ($images_types as $image_type) {
                    ImageManager::resize($tmpfile, $path . '-' . stripslashes($image_type['name']) . '.jpg', $image_type['width'], $image_type['height']);
                    if (in_array($image_type['id_image_type'], $watermark_types)) {
                    Hook::exec('actionWatermark', array('id_image' => $id_image, 'id_product' => $id_entity));
                    }
                }
            } else {
                unlink($tmpfile);
                return false;
            }
            unlink($tmpfile);
            return true;
        }

     

  6. Multi language support.
    As you can see in the above code we call the function createMultiLangField() This function make sure we add our product to all available languages on your store. Add the following function to your script.
        function createMultiLangField($field) {
            $res = array();
            foreach (Language::getIDs(false) as $id_lang) {
                $res[$id_lang] = $field;
            }
            return $res;
        }

     

  7. The last step
    And after this all we come at our last step, adding our first programmatically created product.  This can be done by calling our function addProduct and pass the necessary values.
        addProduct(
            '1234567891234',                         // Product EAN13
            'Tutorial by Crezzur',                         // Product reference
            'Crezzur',                               // Product name
            5,                                       // Product quantity
            'Code by Crezzur (https://crezzur.com)', // Product description
            array(                                  // Product features (array)
                array("name" => "Color", "value" => "Red"),
                array("name" => "Height", "value" => "200cm"),
           ),
            '999.95',                                // Product price
            'https://crezzur.com/img/crezzur-logo-1544601440.jpg',       // Product image
            1,                                       // Product default category
            array(1, 5)                              // All categorys for product (array)
       );

 

For the people that don't want to copy paste all the code we have created a file which contains all of the above the full code file can be found here.

Using the code above will allow you to mass import products using a Ajax call (JSON) our using a CSV file. We do not add this code since the variables for each web service will be different.

---------------- A like and/or a thank you for my work is much appreciated ----------------

 

 

 

Edited by Crezzur (see edit history)
  • Like 1
  • Thanks 2

Share this post


Link to post
Share on other sites
  • 7 months later...

Crezzur,

It was very useful for me but how to add Customization field to this product.

Thank you. 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

Cookies ensure the smooth running of our services. Using these, you accept the use of cookies. Learn More