Creative Meat Blog
Development

Oneupweb : Create a Simple Product Catalog with WordPress Custom Post Types

Posted by Brian in Development, Tutorials on March 14, 2011 - 5:59 pm

What can’t WordPress do these days? The addition of custom post types in 3.0 makes it possible to accomplish all kinds of tasks. Today we will be looking at a simple way to create products with WordPress custom types and sell them with PayPal buy now buttons.

What we will be creating:

How it’s done:

We will leverage a custom post type (available since WordPress 3.0) and custom meta boxes to create the administrative interface for adding products. Our first step will be to create the custom product type.

Step One: Create the custom post type

The following code goes into the functions.php file:

/****************************
 * Let's add the custom post type
 ****************************/

add_action('init', 'catalog_init');
function catalog_init()
{
  $labels = array(
    'name' => _x('Products', 'post type general name'),
    'singular_name' => _x('Product', 'post type singular name'),
    'add_new' => _x('Add New', 'product'),
    'add_new_item' => __('Add New Product'),
    'edit_item' => __('Edit Product'),
    'new_item' => __('New Product'),
    'view_item' => __('View Product'),
    'search_items' => __('Search Products'),
    'not_found' =>  __('No products found'),
    'not_found_in_trash' => __('No products found in Trash'),
    'parent_item_colon' => '',
    'menu_name' => 'Products'

  );
  $args = array(
    'labels' => $labels,
    'public' => true,
    'publicly_queryable' => true,
    'show_ui' => true,
    'show_in_menu' => true,
    'query_var' => true,
    'rewrite' => true,
    'capability_type' => 'post',
    'has_archive' => true,
    'hierarchical' => false,
    'menu_position' => null,
    'menu_icon' => get_bloginfo('template_url') . '/images/producticon.png',
    'supports' => array('title','editor','thumbnail','excerpt')
  );
  register_post_type('product',$args);
}

We hook into the WordPress init action to create the product post type. Notice the register_post_type function accepts the name of the post type and the arguments array. Things to note in the argument array are the menu_icon and labels.

Step 2: Create meta boxes for product information

We want people to be able to pay for these products, so we better create a way for them to do that. We will leverage custom meta boxes for our product post type to get this done in a snap.
Add the following code to the functions.php file:

/**********************************************************************************
 * The custom meta boxes to handle paypal button and product price
 *********************************************************************************/
add_action('add_meta_boxes', 'catalog_add_custom_box');
function catalog_add_custom_box() {
    add_meta_box('catalog_priceid', 'Product Price', 'catalog_price_box', 'product','side');
    add_meta_box('catalog_paypalid', 'PayPal Code', 'catalog_paypal_box', 'product','side');
}

function catalog_price_box() {
    $price = 0;
    if ( isset($_REQUEST['post']) ) {
        $price = get_post_meta((int)$_REQUEST['post'],'catalog_product_price',true);
        $price = (float) $price;
    }
    ?>




<?php
}

function catalog_paypal_box() {
    $code = '';
    if ( isset($_REQUEST['post']) ) {
        $code = get_post_meta((int)$_REQUEST['post'],'catalog_product_paypal',true);
        $code = stripslashes($code);
    }
    ?>





<?php
}

We hook into the add_meta_boxes action here and use the add_meta_box functions to do our dirty work. As you can see this function accepts the type of post this box will be added to (in our case this is product) and a callback function that handles the display of the meta box controls.

Step 3: Save the product info

Saving the product info is as easy as hooking into the save_post action.

add_action('save_post','catalog_save_meta');
function catalog_save_meta($postID) {
    if ( is_admin() ) {
        if ( isset($_POST['catalog_product_paypal']) ) {
            update_post_meta($postID,'catalog_product_paypal',
                                $_POST['catalog_product_paypal']);
        }
        if ( isset($_POST['catalog_product_price']) ) {
            update_post_meta($postID,'catalog_product_price',
                                $_POST['catalog_product_price']);
        }
    }
}

Notice we check that our form values have been submitted before we update our post meta. If you don’t do this you will notice some funky stuff happen as the save_post action can be triggered at different times.

Step 4: Display the product(s)

It is simple to display one of our new products: Let’s just query our custom post type and have some good ol’ fashioned WordPress loop fun. This needs to go inside of a template file. Lets create a single template for our product type. Create a file single-product.php in your theme directory and put the following inside it:

<?php get_header(); ?>
<?php query_posts(array('post_type' => 'product')); ?>
<?php while(have_posts()): the_post(); ?>

<?php the_title(); ?>

<?php the_post_thumbnail(); ?>
<?php echo get_post_meta(get_the_ID(),'catalog_product_price',true); ?>
<?php the_content() ?>
<?php echo get_post_meta(get_the_ID(),'catalog_product_paypal',true); ?>
<?php endwhile; ?> <?php get_footer(); ?>

And…. shazaam! A similar loop would work in any template file. You can have templates to display a single product, or a catalog of them. Experiment with the possibilities!

As you can see WordPress 3.0+ is capable of doing some interesting stuff. Hopefully this tutorial will help you get started on some more robust and interesting ways to utilize this ever growing CMS.

GD Star Rating
loading...
Oneupweb : Create a Simple Product Catalog with WordPress Custom Post Types, 5.0 out of 5 based on 7 ratings

23 Responses to “Oneupweb : Create a Simple Product Catalog with WordPress Custom Post Types”

  1. Really nice post. Exactly what I was looking for. Novice question if I may, am I correct in assuming this would be implemented as a plugin?

  2. Brian says:

    Thanks Richard! The beauty of WordPress custom post types is you can register them from the functions.php file inside of your theme. You could achieve this functionality through a plugin, but I find it is much easier to do so within your theme.

  3. abzal says:

    Thanks for the info! I am looking for a simple product solution for my website. Not happy wiht wp ecommerce and eshop. Hope this will be of help!

  4. Brad says:

    Getting a ‘product’));?> on the return page. Any suggestions?

  5. Brian says:

    It looks like you have a problem with your template file around this line:
    <?php query_posts(array(‘post_type’ => ‘product’)); ?>

    Make sure your php tags are opening and closing properly in your template files. Hope that helps!

  6. Terry says:

    Hi, thanks for the code, but I can’t get it to work.

    There seems to be a problem with the display routine.

    I have read the comment from Brian and it seems I have the same problem

  7. brian says:

    Hi Terry,

    Could you attach a link to your template file? I would be happy to take a peak at it.

    Thanks!

  8. Harness says:

    Brian, great post! Just what I was looking for but more code than I wanted to go in to. Maybe with some Green Snarly Cake I’d have enough energy to tackle it!!

  9. Jen says:

    Thanks. Works perfectly. One issue I’m having is the cents entered get stripped out on a second save so 10.50 becomes just 10. How can I preserve cents?

  10. Jen says:

    Nevermind, I just removed (float)

  11. Brad says:

    Brian,

    I’m still struggling with this (3 months later). Could I get you to look at what I’m doing wrong? If you could email me that’d be great.

  12. Brian says:

    Hi Brad,

    Sorry to hear that. Any way you can attach a link to the files you are working with? I would be happy to take a look.

  13. Martin says:

    thx brian really nice post ;)

  14. Jbasioli says:

    Hi,

    Is it possible that this code is no longer functional because of the WP latest version?
    Because i can’t get it to work, even if i go step by step inputing your code i get this warning:
    Warning: Cannot modify header information – headers already sent by (output started at /home/nolimits/public_html/neutrino/wp-content/themes/neutrino/functions.php:16) in /home/nolimits/public_html/neutrino/wp-admin/theme-editor.php on line 99
    and also some other warnings if i try to input full code.

  15. Brian says:

    Ah. It looks like you are trying to put the output call in the functions file as well. That was my bad. I will be sure to update the post. You need to put the output from step 4 into a template file (page.php,single.php,etc….). Try creating single-product.php and place the template code in there. Don’t forget your header,sidebar and footer functions ;)

  16. Olga says:

    Hi Brian! Thanks a lot! I have successfully implemented your code.
    Do you know how to add product categories to these custom posts by the way :) ?

  17. Olga says:

    Found it: just add
    ‘taxonomies’ => array(‘category’, ‘post_tag’)

    after line: ’supports’ => array(‘title’,'editor’,'thumbnail’,'excerpt’),
    Don’t forget a comma here: ‘excerpt’),

  18. Gomy says:

    How can I have categories for products same as posts have?

  19. Brian says:

    Olga got it right on the nose (see the comment above yours). Since these products are just posts you can use the taxonomies parameter.

  20. Lizy says:

    Funciono perfectamente. Gracias

  21. AQ says:

    This was my introduction to custom post types, and it saved my bacon. Thank you!

  22. Cubicamente says:

    a question, there is a way to call the products in a specific category, and display them on a certain page?

  23. Cubicamente says:

    ‘product’, ‘category_name’ => ‘category-slug’ )); ?> got it. i think

Leave a Reply