Append Tags to Shopify Products Using PHP

I’m using the code below to update hundreds of product tags in Shopify, you might be able to find an app in Shopify but this way seems quicker for me.

This code was tested on API version 2020-01.

PHP 7.2 + Required

This code uses your terminal/command prompt to execute the php script and requires the “write_products” scope in Shopify’s API.

Install the Dependencies

Using composer: composer require phpclassic/php-shopify

The Code

Fill in the $config variable with your store details, make sure "write_products" scope has read/write access.

Edit the line $tags[] = 'Append This Tag'; to add the tags you want to append.

Run the PHP script from your terminal.

<?php

// command line tool used to bulk update tags for products in shopify
// make sure api has access to "write_products" scope
// usage: php update.php

require('vendor/autoload.php');

use PHPShopify\ShopifySDK;

// config
$config = array(
    'ShopUrl' => 'yourshop.myshopify.com',
    'ApiKey' => '***YOUR-PRIVATE-API-KEY***',
    'Password' => '***YOUR-PRIVATE-API-PASSWORD***',
);

// setup $shopify
$shopify = PHPShopify\ShopifySDK::config($config);

// download all the products
$productResource = $shopify->Product();
$products = $productResource->get(['limit' => 250]);
$nextPageProducts = $productResource->getNextPageParams();
$nextPageProductsArray = [];

while ($nextPageProducts) {
    $nextPageProductsArray = $productResource->get($productResource->getNextPageParams());
    $products = array_merge($products, $nextPageProductsArray);
    $nextPageProducts = $productResource->getNextPageParams();
}

// update tags for each product
foreach ($products as $product) {
    if (count($product['variants']) > 0) {
        $tags = explode(",", $product['tags']);
        
        $tags = array_map(function($a) {
            return trim($a);
        }, $tags);
        
        // append tags
        $tags[] = 'Append This Tag';
        
        // delete duplicates
        $tags = array_unique($tags);
        $tags = array_filter($tags);

        // update
        try {
            $shopify->Product($product['id'])->put([
                    'tags' => join(',', $tags)
            ]);
            
            echo sprintf('UPDATE TAG: %d' . PHP_EOL, $product['id']);
        } catch(Exception $e) {
            echo sprintf('UPDATE TAG FAILED: %d' . PHP_EOL, $product['id']);
        }

        // rest
        sleep(0.5);
    }
}

echo PHP_EOL;
echo 'DONE';
echo PHP_EOL;

 

Leave a reply:

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Site Footer

Sliding Sidebar

RYAN OUN

Nice to meet you, my name is Ryan and I build stuff for the web. Welcome to my website where you can learn about me and my interests.

USEFUL LINKS