Using WP e-Commerce

This article first appeared in issue 232 of .net magazine – the world's best-selling magazine for web designers and developers.

More and more websites are turning to WordPress as their CMS, which concurrently increases the number of shops and online businesses using it for their ecommerce needs. With an agglomeration of ecommerce plug-ins available for WordPress, WP e-Commerce stands out as a standardised solution – it’s incredibly powerful and expandable, and works with just about every theme you can think of.

WP e-Commerce continues to grow and, with over 1.3 million downloads, has a formidable following of developers and enthusiastic designers providing sound solutions with a low development footprint to clients of all types and sizes. This tutorial goes into how to set up WP e-Commerce and attain common functionality without having to pay a penny.

Setting up

You’re enthusiastic, excited and prepared for WordPress. You’re installed, up and running and can’t wait to get your shop on the web – but aren’t sure where to start. If you’ve used WordPress before you’ll be accustomed to the admin area already; if not, we’ll get you ready to sell quicker than you’d think.

To install WP e-Commerce head to the plug-in manager in the WordPress admin and search for WP e-Commerce. Hit install; now all you have to do is click activate.

WordPress’s famous one-click install plug-in screen makes extending your package a 30-second task, no matter what your level of experience

WordPress’s famous one-click install plug-in screen makes extending your package a 30-second task, no matter what your level of experience

Once you’re installed you will see a new menu item labelled Products; clicking on this will show you an empty catalogue of products. You can add products here and now, which for the rest of this tutorial is a good idea because we’ll be running through how to retrieve the most popular products and add product searching without paying for the WP e-Commerce gold cart extras.

It may seem obvious to have a ‘popular products’ function, but WP e-Commerce doesn’t come with it by default – luckily it’s a simple piece of functionality to create. For the sake of your business cross-selling is important; it’s also crucial to your customers that they have a pleasant buying experience, and displaying popular products is a great way to better sales and improve user experience.

We need to edit the theme’s functions.php to include our custom functionality. We’ll write a function that adds ‘popular products’ functionality and a shortcode to be able to call the function mid-post/page.

Doing the work

I’m using the brilliant Sticks & Stones theme by Tipsy & Tumbler – it’s very responsive and works brilliantly with WP e-Commerce straight out of the box. Since the theme’s functions.php is already rather large we’re going to create a new file called functions-addons.php, which we’ll save in the same directory as functions.php. You’ll find these files in wp-content/ themes/sticksandstones.

The WordPress Codex is a great resource for learning to get to grips with WP’s integral functions, which are worth putting to use wherever possible

The WordPress Codex is a great resource for learning to get to grips with WP’s integral functions, which are worth putting to use wherever possible

Before we get to the code, the way newer versions of WP e-Commerce work is that when a user adds one of your items to their cart and goes through the checkout, the plug-in writes the items to the table wp_wpsc_cart_contents – whereas older iterations wrote to the database upon adding to the cart.

Querying the database

To get the popular products from the database we need to do two things: expose the WordPress database to the function, and then write a MySQL query to gather the products and order them by frequency of purchase:

//Expose the databaseglobal $wpdb;//Get the results$popular_products = $wpdb->get_results("SELECT 'prodid',SUM(quantity) FROM '{$wpdb->prefix}wpsc_cart_contents' GROUP BY 'prodid' ORDER BY 'quantity' DESC LIMIT {$atts['limit']}", ARRAY_A);

We expose the standard WordPress database adaptor to the function, giving us the ability to query the database and format the results. We can now modify the data in a way we feel comfortable with. For the sake of ease I’ve left the format as an associative array.

The second thing we do is use the MySQL built in SUM functionality, which counts the total number of a field’s values – and our third action is to group the items together by the products ID so we don’t get duplicates in the results and invalidate the results.

Now it may look like we’ve done most of the work – and in a way we have; the painful part is out of the way – but the function isn’t finished. We have to process the data we have into a format that’s both semantic and flexible to use throughout our new shop.

The method we use to go about this is by writing a loop that will go over the data and output our most popular products. To execute our loop we utilise the code below, which individualises the product from the data set we fetched from our query – meaning we can write each out quickly, easily and efficiently.

//Loop through the results<?phpforeach ($popular_products as $item) { $product = get_post($item['prodid']); $the_title = $product->post_title; $the_image = get_the_post_thumbnail($item['prodid']); $the_price = the_product_price($item['prodid']); $the_link = get_permalink($item['prodid']);}?>

We’ll flesh out the loop now with some HTML and I’ll explain the WordPress functions as I use them. A lot of developers that use WordPress don’t know of these functions and write terrible code as a polyfill, slowing the whole site down. I’ll just stick to a two-column layout for the HTML: this is pretty standard for most product pages. This code goes inside the loop:

<div class="product-grid popular-<?php echo $item['prodid']?>"> <a class="popular-name"> <?php echo $the_title?> </a> <a href="<?php echo $the_link?>"> <span class="img"> <?php echo $the_image?> </span> <span class="price"> <span> From only </span> <?php echo $the_price?> </span> </a></div>

You may have noticed a function called in a previous code block named the_product_price. This function is very simple: it just returns the price of the product. It takes two arguments, and if you pass in the second one you will get the special_price. In WP e-Commerce this is simply the sale price, which you can find in the product admin page. The first argument is the product’s ID, which is a unique number given to each product.

function the_product_price($id, $special_price = false) { if ($special_price) { return wpsc_currency_display(get_post_meta($id,'_wpsc_special_price', true)); } else { return wpsc_currency_display(get_post_meta($id, '_wpsc_price', true)); }}

Now to use this as a shortcode within your pages (shortcodes don’t work on posts for some reason) you only need one line of code – it’s another one of those magical WordPress functions. The first argument of the add_shortcode function is a string that you would use within your page; the second argument is the name of the function we’ve just finished writing.

//Add the shortcodeadd_shortcode('popular_products', popular_products);

Improving WordPress search for products

Getting WordPress search to rock your socks instead of sucking harder than a vacuum can be a mammoth task if you need something detailed but there are easier ways to do it. (There’s always an easier way to do something!)

WP e-Commerce is the child of GetShopped; it’s also home to the forum and runs on WP e-Commerce itself selling premium plug-ins

WP e-Commerce is the child of GetShopped; it’s also home to the forum and runs on WP e-Commerce itself selling premium plug-ins

The later versions of WordPress and WP e-Commerce enable you to search products because they’re added as pages, whereas in more elderly versions of WP e-Commerce they were a separate table and separate post type – altogether, a nightmare. Today, luckily, search ‘just works’ – but only just, so we’re going to expand the search to include categories and tags to give your shoppers the best experience possible when browsing your online shop.

Assuming you’ve been adding products to your shop and have already found the categories page within the admin area (under the Products menu we looked at earlier in the tutorial), and you’ve added your categories and your products to them, we can go ahead and start customising our search form and results page. This will make it as easy as possible for your shoppers to get from visitor to putting money in your pocket.

Companies of all sizes are turning to WP e-Commerce’s software – because it’s comprehensive and simple to use, without the cost of development times

Companies of all sizes are turning to WP e-Commerce’s software – because it’s comprehensive and simple to use, without the cost of development times

WordPress has some weird terminologies when it comes to searching specific fields, such as categories not actually being categories – they are called taxonomy and as such we have to do a special query to get them out! So to acknowledge our goals we’re going to customise the search form to include a new field.

First we need to open our search form template in our theme: it’s called searchform.php (if you don’t have one in your theme folder, create one). We’re going to customise the form – open a form tag like this:

<form id="searchform" action="/">

The action is set to root because WordPress will automatically detect the search query and dish the template out for it. We’ll now add our search fields to the body of the form:

<input type="text" name="s" placeholder="Keywords" />

This is the default WordPress search field. The name s is the search parameter that WordPress uses to search the content and title of each post. Although we’re customising the search this parameter will still search the body and title of the product pages.

The placeholder attribute is the default text that, as you start to type, will disappear and automatically reappear if you didn’t enter anything; this would need to be JavaScript controlled by your theme. The Sticks & Stones theme already does this for browsers that don’t support cool attributes. (I’m looking at you, Internet Explorer.)

Let’s add another field so we can search the categories we’ve added:

<input type="text" name="term" placeholder="Categories" />

We’ll be using the field above to search our product taxonomies. The name term is the WordPress default search attribute for taxonomies; your WP e-Commerce products are all under a post type and their categories are all a custom taxonomy.

Finally, let’s add our submit button and close the form tag we started above. This is all incredibly standard stuff – but don’t worry: we’re getting closer to the really cool bit that is changing the way the WordPress search works and getting what we want from it.

<input type="submit" class="submit" name="submit" id="searchsubmit" value="Search" /></form>

Right, that’s our form taken care of. Save it and upload it – you’ll see your new form appear where the search forms used to be. Now let’s take a look at WordPress’s search functionality – what we’re going to be doing is adding a filter to the search function that pulls out results that match our custom taxonomies. This seems really difficult to do, but actually takes just five lines of code; you could say it’s easier than setting up WordPress.

Open your functions.php and add the following block of code to the bottom of it – I’ll explain the code afterwards:

function search_by_tax_filter (&$query) { if ($query->is_search) $query->set('taxonomy', 'wpsc_product_category');}//Add the filteradd_action('parse_query', 'search_by_tax_filter');

This may not look like much, but it actually does a lot – like they say, good things come in small packages.

What we do here is to work from the bottom upwards. We add a filter hook to the WordPress hook system. This means we’ve effectively put a listener in the system and we’re listening every time we construct a query (that’s every page load in this instance).

Now, I always opt for this kind of method since using a new WP_Query damages the rest of the page’s queries, meaning all kinds of crazy things will happen. (That is, if you’re human like myself and every other developer – and you forget to add the wp_reset_query() call at the end of the function creating a new WP_Query.)

This is all kinds of fun – but since we’re using a WordPress function to modify WordPress behaviour, we avoid having to do any of the back-breaking labour. It looks after itself.

The function above, where we’re adding the hook, checks that the query we’re running is a search query (not a generic query). We then add a new search clause to the query it’s currently building – we only want WP e-Commerce’s product category (the search term comes from our form field) to appear in the results.

The brilliant, free Sticks & Stones theme by Tipsy & Tumbler is responsive and needs no tinkering to play with WP e-Commerce

The brilliant, free Sticks & Stones theme by Tipsy & Tumbler is responsive and needs no tinkering to play with WP e-Commerce

Now we have our search working we need to do a few more things to it to make it actually useful, since if you test it by filling out just the category you’ll get a list of all of your posts but no products. This is because we haven’t entered a search term – and WordPress doesn’t count this as a valid search so sets the is_search variable to false, meaning our query is never modified and the results are invalid.

This is less than helpful, so what we need to do is have our search redirect to the categories page and list the products within there rather than modify global WordPress behaviour. The reason we would want a redirect is that we don’t want to edit core WordPress behaviour, because we won’t be able to update and so may introduce security issues (also the lack of updates means we’re missing out on important security fixes and feature updates).

So let’s look at how to get the category as a definitive go-to for the redirect and get these searches running smoothly for all your buyers.

First we need to know whether we have a valid search or not. If we don’t have a valid category we should set this as our search query and perform a search there. This will by default return nothing and your formatted ‘no results’ page, or if it does find something it will display that: all angles taken care of.

Let’s look at how we’re going to check for the query string, again using hooks. WordPress knows how to look after WordPress so let’s keep at it. Start by opening a function body in functions.php and adding this code to it:

function fix_empty_search ($query) { global $wp_query; if (isset($_GET['s']) && empty($_GET['s'])) {

The code above does three things: first, it checks for a search parameter in the URL and then it checks if it has a value. If it passes that level of validation we have a candidate for checking within WP e-Commerce if it is a valid category to redirect to.

To check if we have a valid category we use the following block of code:

if (get_term_by('slug', $wp_query->query_vars['term'], 'wpsc_product_category')) wp_redirect("/?wpsc_product_category={$_GET['term']}");else $query->set('s', $_GET['term']);

This uses the WordPress function get_term_by to check whether the category exists. If it does, the function will return an object containing the details of the category, and if it doesn’t exist it will return false, which is perfect for our little check. If the function doesn’t return false it’s a valid category, and we use the wp_redirect function to redirect the user to the category page – and if it isn’t a valid category, it will re-perform the search using the category as the search term in the hope the user can find something close to what they were looking for.

Discover the best free WordPress themes for designers at our sister site, Creative Bloq.

Thank you for reading 5 articles this month* Join now for unlimited access

Enjoy your first month for just £1 / $1 / €1

*Read 5 free articles per month without a subscription

Join now for unlimited access

Try first month for just £1 / $1 / €1

The Creative Bloq team is made up of a group of design fans, and has changed and evolved since Creative Bloq began back in 2012. The current website team consists of seven full-time members of staff: Editor Georgia Coggan, Deputy Editor Rosie Hilder, Deals Editor Beren Neale, Senior News Editor Daniel Piper, Digital Arts and Design Editor Ian Dean, Tech Reviews Editor Erlingur Einarsson and Ecommerce Writer Abi Le Guilcher, as well as a roster of freelancers from around the world. The 3D World and ImagineFX magazine teams also pitch in, ensuring that content from 3D World and ImagineFX is represented on Creative Bloq.