7 days of WordPress plugins, themes & templates - for free!* Unlimited asset downloads! Start 7-Day Free Trial
  1. Code
  2. Creative Coding

WordPress and PayPal: An Introduction

Scroll to top
Read Time: 15 mins

For this tutorial we will go through the steps involved to integrate PayPal as your Payment Service Provider for a WordPress powered site. Working with Custom Post Types we will create a basic shopping cart and allow for payments to be taken via PayPal. Whilst the worked example is functional, you should take further steps to sanitise and store data when working with payments.


We will utilise custom WP-Admin pages for viewing orders, custom post types for product creation (Jeffrey Way's CPT class) and custom page templates for viewing products, cart and processing. Our raw function will be created in PHP and we will apply some basic styling with CSS.

Within the code snippets below some markup may have been stripped for readability.

For those who opt-in here please advance to go and collect $200 or skip to stage 2 of this tutorial and benefit from sample data.

Step 1 WP-Admin and Page Structure


Let's publish the pages in WP-Admin we will use throughout the tutorial.

  1. Cart
  2. Products
  3. Thank you

We will re-visit these pages and allocate a custom template to each later.

Step 2 Child Theme Structure


Now we will create the directories and files required for our project.

We are making a child theme from Twenty Ten here, we only need to create the files we will be modifying or creating from scratch. Any others that are required e.g. footer.php WordPress will fill in the blanks for us.

Step 3 Jeffrey Way's Custom Post Types

We will work with Jeffrey Way's class (requires PHP 5.3) to create a product custom post type
which will allow creation of products, and not blog posts pretending to be products, via WP-Admin.

Custom Post Type - ProductsCustom Post Type - ProductsCustom Post Type - Products

In the file /wppp/wppp/post_types.php add the following pieces of code.

First we will include the class.

Secondly, create a new Custom Post Type and identify which components of the write page to use.

Thirdly we have one specific field that's better suited with a text field on its own. Price.

When all together it will look like this.

Step 5 Retrieving All Products

Product listProduct listProduct list

WordPress Custom Post Types are fantastic and with Jeffrey's class implementation can be fast. The custom data can be accessed very quickly, much like you would blog posts within "the loop".

Let's visit wppp/tpl-products.php file and retrieve the products.

This is a convention WordPress requires of us to create a custom template. Provided the active theme holds this file we can assign it to any page.

Go ahead and assign this template to the products page previously published.


Next we create a new instance of WP_Query and look for
a post_type of "product".

Using WP_Query we have access to many template tags existing within WordPress.

All that's required now is to loop over the products and output the data.

get_post_meta(); will retrieve data stored within custom fields, and since a meta box was added using JW's class earlier this is what to use in order to retrieve its value.

Notice we use "product_info_price" as the second parameter for get_post_meta. This is the name applied to our custom field when utilising JW's CPT class. The convention appears to be name-of-post-type_info_field.

Step 6 Retrieving a Single Product

Single productSingle productSingle product

WordPress will serve single-custom-post-type.php if a custom post type exists and a file single-custom-post-name.php exists within the active theme. This is helpful when creating a new template for single products.

Much like retrieving multiples we could utilise WP_Query (for custom queries) and the template tags WordPress provides. However when viewing a single item, technically we no longer need a loop or a custom WP_Query.

One more addition to our single-product.php file, a form which will allow this item to be added to the shopping cart session.

Two hidden fields have been added to this form, 1 which will store the post ID (or product ID) and the other will be used a little later. A default quantity of 1 is also set.

Step 7 Adding an Item to the Session

The "Add to cart" button resides on the single product page as illustrated in the previous step, after a user has chosen to add a product the form will be sent to the cart page.

Let's work with the wppp/tpl-cart.php file now.

tpl-cart.php is a custom template so we need to let WordPress know and assign the template to the cart page via WP-Admin.

Now we check if suitable post data has been sent and if true we store data for convenience as variables.

Using a switch to determine the current action and process accordingly.

To print the cart to the page a loop is used to iterate over the session data.

Whilst in this loop we query for human readable data instead of the numeric representation of each product / post stored within the session.

To do this get_post() is perfect which allows for a quick way to query WordPress by passing a post ID. The data returned is a scaled down version of WP_Query and it is stored within $row.

$row can now be printed to the page along with a running total showing the price of product multiplied by the quantity.

Within the loop a form is placed which, for convenience will allow a user to remove an item entirely from their cart.

Using the switch written earlier a check for the case of "remove" will allow for the item to be removed from the session.

Step 8 Preparing for PayPal

PayPal provides a number of ways to send and retrieve data, we'll be using Instant Payment Notification or IPN.

In order for PayPal to calculate and process any transactions, data can be sent by a form with fields matching the naming and expected data conventions as set out by PayPal.
The IPN guide can be found in the header or the footer menus of paypal.com/ipn.

Let's move on... within tpl-cart.php, underneath all a form is added with the bare essential PayPal requirements.

Check out developer.paypal.com for a sandbox and testing environment.

Once logged into your developer account you will be able to create test buyer and seller accounts and "Enter sandbox test site".

Sending the cart to "https://www.sandbox.paypal.com/cgi-bin/webscr" will allow use of the test environment.

Should you decide to go live, the URL for the form action would simply change to "https://www.paypal.com/cgi-bin/webscr".

developer.paypal.com can be a buggy and a slow experience, have patience. Writing this tutorial I had to wait for PayPal to fix itself and return a couple of hours later.

Much like the previous session loop the data is retrieved and presented with a combination of raw PHP and a WordPress function.

Provided you send PayPal the correct type of data it will be processed via IPN.

In the form above product name, related quantities and prices for each product are all sent. PayPal will perform the calculation this time for multiples based on price per item and quantity.

"Transaction and notification variables" as described in the IPN Guide have been implemented as hidden form fields much like the other variable types directed by PayPal.

Passing an email to the input with a name of "business" instructs PayPal which account is the seller. Here for convenience we use the current WordPress administrator's email.

business - Email address or account ID of the payment recipient (that is, the
merchant). Equivalent to the values of receiver_email (if payment is
sent to primary account) and business set in the Website Payment
- IPN Guide -

The 3 URLs passed with the form (return, cancel_return and notify_url) allow for links to be placed within the checkout process as a user visits paypal.com from the cart. The "cancel" URL will be shown before and during the transaction, whilst "return" is shown after the transaction.

You could say the most important field here is "notify_url" which allows a developer to listen for PayPal instructions behind-the-scenes as the user processes their transaction.

When PayPal sends a response to the ipn.php file the transaction details can be stored within a database, emails can be sent and downloads presented. It is up to you to process the data using methods that reflect the product type for sale.

So let's create the database table in the ipn.php file and move onto retrieving orders.

Step 9 Database


For speed of implementation a longtext field for items_ordered is created to store the items purchased with each order and the quantity as serialized data. It may be advisable with a live store to normalise any database tables behind your store to 4NF or consider using a Custom Post Type when storing orders.

Step 10 Testing

PayPal Developer SandboxPayPal Developer SandboxPayPal Developer Sandbox

Now you should be able to publish new products, add a product(s) to the cart session, view the shopping cart session and proceed to PayPal.

After a customer has paid for goods at PayPal, what then? How can we identify if the transaction has been successful, which goods have been purchased and where should they be shipped?

In Step 8 buyer and seller accounts were highlighted for test purchases.

Also, previously "return_url" was created as a hidden form field within tpl-cart.php, this file could be used if the user should chose to "Return to merchant site" after the transaction at PayPal.

Looping over post data will show what's going on.

This loop will print any returned data from PayPal via post. You might decide to use this for storing data, it's really not practical to do so.

To arrive at the thank you page we are hoping the user will click "Return to merchant website" from PayPal. In the event a user decides to close the browser what then?

Because of this pitfall all that should be done via tpl-thankyou.php is to empty the cart and display the content as shown below.

We are then notified from PayPal no matter what the user decides to do after payment. This is where the "Notification" of Instant Payment Notification comes in.

When the form was initially sent to PayPal "notify_url" had a value. This instructed PayPal that we would like to use the file http://yoursite.com/wp-content/themes/wppp/ipn.php for communication.

With this in mind we can now "listen" to PayPal (and not the user) for updates on the payment status and process. Let's create that final file and name it ipn.php.

The above code looks a little bit scary, you can see how it is pieced together by looking at the simplified code-sample.php over at PayPal.

Without explaining the example PayPal has given as a guide, we are listening for VALID or INVALID responses and processing accordingly. WPDB is used to store any required data returned by PayPal.

This snippet loops over post data and checks if the current item is an item_name_x which we know is our product's name. The data is then serialised and stored within an array.

The WPDB insert method is used later to send the serialized data along with other values to the customers table.

Step 12 WP-Admin Orders Page


Our final step involves creating a WP-Admin menu page and populating that page with the customers / orders data previously stored.

You may decide to create a more robust orders page to allow for pagination, marking each item for shipping, easy printing of shipping labels and anything else.

Let's follow the style conventions of WordPress and create a reasonably well presented long list of orders.

add_menu_page() is executed with 6 parameters of a possible 7.

  1. Page title
  2. Menu title
  3. User role
  4. URL for our options page. Instead of competing for rank we use the file location and name
  5. Function to execute whilst accessing this page
  6. Icon for the menu

An optional parameter "menu position" could be passed but again let's not wrestle with other Authors.

Above, a function is created, and within, some markup to display the orders. When adding the new menu page this function was also passed which instructs WordPress to execute this code when viewing the corresponding menu page.

Using wpdb to output the orders will be the final stage.

When sending products and quantities to the database the data was serialized. It's now time to reverse that with unserialize at each iteration.

A nested loop allows each line of unserialized data to be split and shown as list items.

Finally the functions created previously are executed using the add_action function and the admin_menu action specifically. For a full list of actions visit the Action reference.


In this tutorial a combination of best practices, hacks and techniques have been shown much of which will be open for debate. Some code and discussion has been omitted from the tutorial, namely additional.css, and functions.php.

additional.css is imported within the stylesheet for Twenty Ten (style.css) and applies some basic styles for the display throughout the example.

functions.php requires any files for custom posts and viewing orders within WP-Admin. A new image size is also set which crops the product thumbnail to match.

We make use of Twenty Ten's menu capability to show the top menu links for "Products" and "Cart".

Let us know in the comments what you think of this introduction to using PayPal with WordPress.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.