Snipcart for WordPress: A Simple, Shortcode-Based Integration

In my work as a WordPress developer, I spend a lot of time on e-commerce sites. These sites generally use either WooCommerce or Easy Digital Downloads, the most popular e-commerce plugins for WordPress.

The other thing I know about is PayPal, which has simple purchase buttons that I use on occasion.

The Limitations of WooCommerce, EDD, and PayPal

I personally love WooCommerce, but that doesn’t mean I’m blind to its potential drawbacks:

  1. Can definitely be overkill for simple transactions: it adds various pages, custom post types, and other structure to the site.

  2. No integrated payment gateway: PayPal is available by default, but full-featured gateways intended for credit cards must be integrated separately.

EDD is beautifully written by one of the best plugin developers out there, Pippin Williamson. Its obvious limit, though, is that it only handles downloads—not tangible, shippable products.

PayPal is, of course, a really well-known payment gateway. It’s fairly simple to use, but it has its own issues:

  1. Not terribly full-featured: you get the button with some potential dropdown options, and that’s it.

  2. Not all that easy to customize: the old-school code you paste in pretty much always looks and acts like a stock PayPal button unless you get really creative.

Snipcart, Eh?

I was intrigued to hear about Snipcart, whose value proposition—as best as I understand it—is "simpler, better e-commerce," with an emphasis on minimal code and a minimal e-commerce backend.

Snipcart does seem to have a bit of a checkered history with WordPress, including a cancelled plugin. This isn’t that surprising, given WordPress’s unique ways of handling data: Snipcart works through HTML code paste-ins, and WordPress has too much going on under the hood to accommodate that easily.

So I thought I’d present the code for a simple WordPress integration in Snipcart. It’s short—around 50 lines of code—and dead-simple: it doesn’t add any admin pages, settings lists, etc., and you control it with a simple shortcode that you can drop anywhere in your posts, widgets, and pages.

Integrating Snipcart with WordPress: The Code

// This loads snipcart.js (after jquery.js!) and snipcart.css
add_action( 'wp_enqueue_scripts', 'pressup_snipcart_scripts' );
function pressup_snipcart_scripts() {
    // JS that gives the search box a default value
    wp_enqueue_script( 'snipcart', 'https://app.snipcart.com/scripts/snipcart.js', array( 'jquery' ) );
    wp_enqueue_style('snipcart-theme', 'https://app.snipcart.com/themes/base/snipcart.css');
}

// This adds the "id" and "data-api-key" parameters to the snipcart.js <script> tag
add_filter('clean_url','pressup_snipcart',10,3); 
function pressup_snipcart( $good_protocol_url, $original_url, $_context){
    if ( FALSE === strpos($original_url, 'snipcart') or FALSE === strpos($original_url, '.js')) {
        return $original_url;
    } else {
        remove_filter('esc_url','pressup_snipcart',10,3);
        $url_parts = parse_url($good_protocol_url);
        return $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'] . "' id='snipcart' data-api-key='YOUR_API_KEY";
    }
}

// This adds the shortcode to control your purchase buttons
add_shortcode( 'snipcart-button', 'pressup_snipcart_button' );
function pressup_snipcart_button( $atts ) {
    $a = shortcode_atts( array(
    'text' => 'Purchase',
    'class' => 'snipcart-add-item',
    'data_item_id' => '',
    'data_item_name' => '',
    'data_item_price' => '',
    'data_item_url' => '',
    'data_item_description' => '',
    'data_item_image' => '',
    'data_item_weight' => '',
    'data_item_max_quantity' => '',
    'data_item_stackable' => '',
    'data_item_shippable' => '',
    'data_item_quantity' => '',
    'data_item_taxable' => '',
    ), $atts );

    $required = array(
        'data_item_id',
        'data_item_name',
        'data_item_price',
        'data_item_url',
    );

    // Return a failure message if not all required fields are present
    foreach($required as $value) {
        if(!(isset($a[$value])) || $a[$value] === '' ) {
            return '[Purchase button needs value for ' . $value . ']';
        }
    }

    // Building the <a> tag that will be the purchase link
    $return = '<a href="#" ';

    foreach($a as $key => $value) {
        if($key === 'class' && $value !== 'snipcart-add-item') {
            $return .= $key .'="';
            $return .= 'snipcart-add-item ' . $value;
            $return .= '" ';
        }
        elseif($key === 'text' || $value === '') {
            continue;
        }

        else {
            $key_hyphens = str_replace('_', '-', $key);
            $return .= $key_hyphens . '="';
            $return .= $value;
            $return .= '" ';
        }
    }

    $return .= '>' . $a['text'] . '</a>';

    return $return;
}

How to Use It

There are a few very simple steps here.

1. Paste code Into functions.php or a plugin

This code needs to go into the functions.php file of your active WordPress theme; or, better yet, it can work as a standalone plugin. If you’d like to know the process for creating a basic plugin, you can check out a tutorial we’ve written on the subject. All the actual logic is written out, so you’ll just need to name the plugin, upload it correctly, and activate it.

2. Change YOUR_API_KEY

Search for YOUR_API_KEY in the code you pasted in. You need to replace that with your actual Snipcart API key. Make sure you don’t change anything around it, like the quotation marks.

3. Use a Shortcode for your Purchase Buttons

The way to actually make purchase buttons show up in your posts and pages is through the shortcode we registered, [snipcart-button].

A sample use of the shortcode is as follows:

[snipcart-button text="Buy Bacon" class="bacon-button" data_item_id="24" data_item_name="bacon" data_item_price="1.25" data_item_url="https://wpshout.com/" data_item_weight="20"]

And that gets you this:

<a href="#" class="snipcart-add-item bacon-button" 
   data-item-id="24" 
   data-item-name="bacon" 
   data-item-price="1.25" 
   data-item-weight="20">Buy Bacon</a>

Shortcode Parameters

As in the example above, your purchase options are included through shortcode parameters. The full list of shortcode parameters is in the code above; it starts with text (the text of the purchase link) and ends with data_item_taxable. Most fields correspond to Snipcart fields as listed here, with two exceptions:

  1. text is the text of the purchase link.

  2. class allows you to add CSS classes to the purchase link. Classes will be placed in addition to the required class, snipcart-add-item.

Note: Please note that because of limitations with how shortcode fields can be named, shortcode fields are named with underscores_like_this rather than dashes-like-this.

Required Parameters

As with Snipcart itself, the shortcode has four required parameters:

  1. data-item-id

  2. data-item-name

  3. data-item-price

  4. data-item-url

The shortcode won’t work without these; more generally, Snipcart itself can’t work if you don’t specify them.

That’s It!

I hope this will make it easy for you to use Snipcart in WordPress. I think Snipcart could be good for people who want a very simple selling experience that is still easy to configure visually—so hopefully this will help more WordPress folks see it as an option.

One next step from here would be to turn the code into a plugin. We’ve thought about doing it ourselves; it’d take a bit of work, like turning the API key into a field that gets set in the WordPress admin, but should certainly be doable. If you use WordPress and would love a quick-and-easy plugin to get up and running with Snipcart, let us know in the comments below!

Thanks for reading! And don’t forget to check out our technical WordPress writing at WPShout.

About the author

Fred Meyer

Fred Meyer is an online consultant and WordPress developer. He loves to think and write about WordPress at WPShout, and he helps clients meet their business goals online at Press Up.

36 000+ geeks are getting our monthly newsletter: join them!