PHP code example of craftcms / shopify

1. Go to this page and download the library: Download craftcms/shopify library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

craftcms / shopify example snippets


use craft\base\Event;
use craft\events\DefineGqlTypeFieldsEvent;
use craft\gql\TypeManager;
use craft\shopify\elements\Product;
use GraphQL\Type\Definition\Type;

Event::on(
    TypeManager::class,
    TypeManager::EVENT_DEFINE_GQL_TYPE_FIELDS,
    function(DefineGqlTypeFieldsEvent $event) {
        // Exit early unless it’s the “type” definition we want to modify:
        if ($event->typeName !== Product::GQL_TYPE_NAME) {
            return;
        }

        // Register a new field that can resolve the supplemental `data`:
        $event->fields['shopifyCategory'] = [
            'name' => 'shopifyCategory',
            'type' => Type::string(),
            'description' => 'The Shopify “Standard Product Taxonomy” name.',
            'resolve' => function(Product $source) {
                return $source->getData()['category']['name'] ?? null;
            },
        ];
    }
)

if ($event->typeName === \craft\shopify\elements\Product::GQL_TYPE_NAME) {
    // Manipulate product element fields...
}

if ($event->typeName === \craft\shopify\gql\types\Image::getName()) {
    // Manipulate fields on "image" objects...
}

$event->fields['edges']['node']['collections'] = [
    'title',
    'handle',
    'description',
    // ...
];

use craft\base\Event;
use craft\shopify\events\ShopifyProductSyncEvent;
use craft\shopify\services\Products;

Event::on(
  Products::class,
  Products::EVENT_BEFORE_SYNCHRONIZE_PRODUCT,
  function(ShopifyProductSyncEvent $event) {
    // Example 1: Cancel the sync if a flag is set via a Shopify metafield:
    $metafields = $event->element->getMetafields();

    if ($metafields['do_not_sync'] ?? false) {
      $event->isValid = false;
    }

    // Example 2: Set a custom field value from metafield data:
    $event->element->setFieldValue('myNumberFieldHandle', $metafields['cool_factor']);
  }
);

use craft\base\Event;
use craft\shopify\events\DefineGqlFieldsEvent;
use craft\shopify\services\Api;

Event::on(
    Api::class,
    Api::EVENT_DEFINE_PRODUCT_GQL_FIELDS,
    function(DefineGqlFieldsEvent $event) {
        // Select data for Shopify's Standard Product Taxonomy
        // https://shopify.github.io/product-taxonomy/releases/2026-02/
        $event->fields['edges']['node']['category'] = [
            'fullName',
            'id',
            'name',
        ];
    }
);

use craft\base\Event;
use craft\shopify\events\DefineGqlQueryArgumentsEvent;
use craft\shopify\services\Api;

Event::on(
    Api::class,
    Api::EVENT_DEFINE_GQL_QUERY_ARGUMENTS,
    function(DefineGqlQueryArgumentsEvent $event) {
        // Skip if we’re not querying products:
        if ($event->fieldName !== 'products') {
            return;
        }

        // For product queries only sync products that belong to a specific collection:
        $syncCollectionId = 'collection_id:108179161409';
        if (array_key_exists('query', $event->arguments)) {
            $event->arguments['query'] .= ", {$syncCollectionId}";
        } else {
            $event->arguments['query'] = $syncCollectionId;
        }
    }
);

use craft\shopify\elements\Product;

return [
  'endpoints' => [
    'products.json' => function() {
      return [
        'elementType' => Product::class,
        'criteria' => [
          'publishedScope' => 'web',
          'with' => [
            ['myImageField']
          ],
        ],
        'transformer' => function(Product $product) {
          $image = $product->myImageField->one();

          return [
            'title' => $product->title,
            'variants' => $product->getVariants(),
            'image' => $image ? $image->getUrl() : null,
          ];
        },
      ];
    },
  ],
];
bash
   php craft plugin/install shopify
   
bash
php craft shopify/api/query 'mutation deleteWebhook {
  webhookSubscriptionDelete(id: "gid://shopify/WebhookSubscription/123456789") {
    userErrors {
      field
      message
    }
    deletedWebhookSubscriptionId
  }
}'
sh
php craft shopify/sync/products

products/{handle}
twig
{# Standard element title: #}
{{ product.title }}
  {# -> Root Beer #}

{# Shopify HTML content: #}
{{ product.descriptionHtml|raw }}
  {# -> <p>...</p> #}

{# Tags, as list: #}
{{ product.tags|join(', ') }}
  {# -> sweet, spicy, herbal #}

{# Tags, as filter links: #}
{% for tag in tags %}
  <a href="{{ siteUrl('products', { tag: tag }) }}">{{ tag|title }}</a>
  {# -> <a href="https://mydomain.com/products?tag=herbal">Herbal</a> #}
{% endfor %}

{# Images: #}
{% for media in product.images %}
  <img src="{{ media.image.url }}" alt="{{ media.image.altText }}">
    {# -> <img src="https://cdn.shopify.com/..." alt="Bubbly Soda"> #}
{% endfor %}

{# Variants: #}
<select name="variantId">
  {% for variant in product.variants %}
    <option value="{{ variant.id }}">{{ variant.title }} ({{ variant.price|currency }})</option>
  {% endfor %}
</select>
twig
{% set product = craft.shopifyProducts.one() %}

<form action="{{ craft.shopify.store.getUrl('cart/add') }}" method="post">
  <select name="id">
    {% for variant in product.getVariants() %}
      <option value="{{ variant.id }}">{{ variant.title }}</option>
    {% endfor %}
  </select>

  {{ hiddenInput('qty', 1) }}

  <button>Add to Cart</button>
</form>