Integrating Amazon Products in Marketpress - Tutorial

Hi WPMU Devers,

OK so I promised Mason and James that I would start adding useful stuff to the forum. So this is my first addition and a wee tutorial to help those wishing for a better way to display Amazon products via MP.

First off what do I mean by "integrating", well I mean using the image from Amazon as your featured image. Currently in WP there is no way to show an image fetched from another site i.e. Amazon as your featured image. Perhaps its coming in 3.5 which will make this tut reduntant pretty quickly....ah well.

What you will need:
1. Marketpress plugin installed....duh
2. Custompress plugin installed
3. Code editor program (I use Dreamweaver)
4. You need to be an Amazon affiliate
5. A whisky (Single Malt, possibly Speyside and finished in a sherry cask...optional)

OK so Im assuming you already have MP with some test products and custompress installed and working correctly.

Create your custom field
Click on Content Types under the Custompress menu (note this is in your network admin panel if you have multisite installed). Then click on the Custom Fields tab and the Add Custom Field button. (see first screenshot)

Fill out the title field I chose "Amazon Image". Under Post Type make sure and select; Product! Add the custom field via blue button and that will add a new custom field to the add/edit Product page (see screensot 2), put the image url from your amazon affiliate product here. Well done, now take a sip of whisky.

Using your new custom field to display a featured image from a URL
OK so at this point we need to use this custom field in our custom MP template. If you dont know how to make a custom MP template then get reading Themeing_MarketPress.txt found in marketpress/marketpress-includes/themes

The two templates Ive made so far are:

mp_product.php
mp_productlist.php

Im sure that other templates and perhaps widgets which will also require tweaking but I havent done this yet and if there is then the principles will be the same as the two above.

So lets do mp_product.php first, not ready? OK take a sip of whisky.

I'll just dump all the code within my post div and then explain it:

<div class=&quot;entry&quot;>
						<?php
						$amazonurl = get_post_meta($post->ID, '_ct_text_507991f6b6920', true);
						if ( $amazonurl == &quot;&quot;) {
							mp_product_image(true, 'single', null);
						} else { ?>
                            <a id=&quot;product_image-<?php the_ID(); ?>&quot; class=&quot;mp_product_image_link&quot; href=&quot;<?php echo $amazonurl; ?>&quot;><img src=&quot;<?php echo $amazonurl; ?>&quot; class=&quot;alignleft mp_product_image_single wp-post-image&quot; width=&quot;175&quot; /></a>
                        <?php } ?>

                        <?php the_content(); ?>
                        <div class=&quot;mp_product_meta&quot;>
							<?php  mp_product_price();
                            //button
                            mp_buy_button(true, 'single', null);?>
                        </div>
                        <?php echo mp_category_list($product_id, '<div class=&quot;mp_product_categories&quot;>' . __( 'Categorised in ', 'mp' ), ', ', '</div>'); ?>
                        <?php echo mp_tag_list($product_id, '<div class=&quot;mp_product_tags&quot;>', ', ', '</div>'); ?>
					</div>

Right so we need to add the contents of our custom field to a variable for ease of use. To do this go back to the Custom Press->Content Types admin page, there you will see the new field you created, hover over it and select the Embed Code link. This gives you the shortcode with custom field key we need prefixed by "id=" (see screenshot 3). Replace my key from line 1 with yours i.e.
$amazonurl = get_post_meta($post->ID, 'YOUR KEY HERE', true);
Ok so we now have an URL from the custom field stored in the $amazonurl variable. Now we just have to stick it in an <img> tag right? Well yes but we also want the ability to add our own products and so use the native WP featured image function. So Ive added a conditional IF statement which will use the native WP featured image if $amazonurl is emtpy.

Ive used a width of 175px in the <img> tag so change this to suit your theme, the height should adjust automagically.

Then we display the product content, price, buy button, category list and tag list. You will notice rather than mess about with shortcodes Im just linking in to the actual functions from template-functions.php feel free to use the shortcodes if your more comfy with them.

Upload that and visit your test product page. Woohoo the product page displays the Amazon image! Ahhhhh sip of whisky.

OK lets do the main product list now which was a bit more of a challenge. This is your mp_productlist.php file. So to list the products we would link into the mp_list_products in template-functions.php but wait that would just spew out the products with the featured image and not have our nice conditional statement that we used earlier. Damn, better take a sip of whisky. OK no problem all we have to do is copy the whole mp_list_products function over to your themes functions.php and rename it, I called mine thepath_list_products and I will dump the code again and review the necessary changes:

function thepath_list_products( $echo = true, $paginate = '', $page = '', $per_page = '', $order_by = '', $order = '', $category = '', $tag = '' ) {
  global $wp_query, $mp;

  //setup taxonomy if applicable
  if ($category) {
    $taxonomy_query = '&product_category=' . sanitize_title($category);
  } else if ($tag) {
    $taxonomy_query = '&product_tag=' . sanitize_title($tag);
  } else if (isset($wp_query->query_vars['taxonomy']) && ($wp_query->query_vars['taxonomy'] == 'product_category' || $wp_query->query_vars['taxonomy'] == 'product_tag')) {
    $term = get_queried_object(); //must do this for number tags
    $taxonomy_query = '&' . $term->taxonomy . '=' . $term->slug;
  } else {
    $taxonomy_query = '';
  }

  //setup pagination
  $paged = false;
  if ($paginate) {
    $paged = true;
  } else if ($paginate === '') {
    if ($mp->get_setting('paginate'))
      $paged = true;
    else
      $paginate_query = '&nopaging=true';
  } else {
    $paginate_query = '&nopaging=true';
  }

  //get page details
  if ($paged) {
    //figure out perpage
    if (intval($per_page)) {
      $paginate_query = '&posts_per_page='.intval($per_page);
    } else {
      $paginate_query = '&posts_per_page='.$mp->get_setting('per_page');
		}

    //figure out page
    if ($wp_query->query_vars['paged'])
      $paginate_query .= '&paged='.intval($wp_query->query_vars['paged']);

    if (intval($page))
      $paginate_query .= '&paged='.intval($page);
    else if ($wp_query->query_vars['paged'])
      $paginate_query .= '&paged='.intval($wp_query->query_vars['paged']);
  }

  //get order by
  if (!$order_by) {
    if ($mp->get_setting('order_by') == 'price')
      $order_by_query = '&meta_key=mp_price_sort&orderby=meta_value_num';
    else if ($mp->get_setting('order_by') == 'sales')
      $order_by_query = '&meta_key=mp_sales_count&orderby=meta_value_num';
    else
      $order_by_query = '&orderby='.$mp->get_setting('order_by');
  } else {
  	if ('price' == $order_by)
  		$order_by_query = '&meta_key=mp_price_sort&orderby=meta_value_num';
    else
    	$order_by_query = '&orderby='.$order_by;
  }

  //get order direction
  if (!$order) {
    $order_query = '&order='.$mp->get_setting('order');
  } else {
    $order_query = '&order='.$order;
  }

  //The Query
  $custom_query = new WP_Query('post_type=product&post_status=publish' . $taxonomy_query . $paginate_query . $order_by_query . $order_query);

  //allows pagination links to work get_posts_nav_link()
  if ($wp_query->max_num_pages == 0 || $taxonomy_query)
    $wp_query->max_num_pages = $custom_query->max_num_pages;

  $content = '<div id=&quot;mp_product_list&quot;>';

  if ($last = $custom_query->post_count) {
    $count = 1;
    foreach ($custom_query->posts as $post) {

			//add last css class for styling grids
			if ($count == $last)
			  $class = array('mp_product', 'last-product');
			else
			  $class = 'mp_product';

      $content .= '<div '.mp_product_class(false, $class, $post->ID).'>';
      $content .= '<h3 class=&quot;mp_product_name&quot;><a href=&quot;' . get_permalink( $post->ID ) . '&quot;>' . $post->post_title . '</a></h3>';
      $content .= '<div class=&quot;mp_product_content&quot;>';
	  $amazonurl = get_post_meta($post->ID, '_ct_text_507991f6b6920', true);
			if ( $amazonurl == &quot;&quot;) {
				$product_content = mp_product_image( false, 'list', $post->ID );
			} else {
				$product_content = '<a id=&quot;product_image-' . $post->ID . '&quot; class=&quot;mp_product_image_link&quot; href=&quot;' . $amazonurl . '&quot;><img src=&quot;' . $amazonurl . '&quot; class=&quot;alignleft mp_product_image_single wp-post-image&quot; width=&quot;175&quot; /></a>';
	  		} 

      if ($mp->get_setting('show_excerpt'))
        $product_content .= $mp->product_excerpt($post->post_excerpt, $post->post_content, $post->ID);
      $content .= apply_filters( 'mp_product_list_content', $product_content, $post->ID );
      $content .= '</div>';

      $content .= '<div class=&quot;mp_product_meta&quot;>';
      //price
      $meta = mp_product_price(false, $post->ID);
      //button
      $meta .= mp_buy_button(false, 'list', $post->ID);
      $content .= apply_filters( 'mp_product_list_meta', $meta, $post->ID );
      $content .= '</div>';

      $content .= '</div>';

      $count++;
    }
  } else {
    $content .= '<div id=&quot;mp_no_products&quot;>' . apply_filters( 'mp_product_list_none', __('No Products', 'mp') ) . '</div>';
  }

  $content .= '</div>';

  if ($echo)
    echo $content;
  else
    return $content;
}

Basically the changes Ive made are really taking the hard work we did in mp_product.php and convert it into the right syntax to use in the new function. So this section:

$amazonurl = get_post_meta($post->ID, '_ct_text_507991f6b6920', true);
			if ( $amazonurl == &quot;&quot;) {
				$product_content = mp_product_image( false, 'list', $post->ID );
			} else {
				$product_content = '<a id=&quot;product_image-' . $post->ID . '&quot; class=&quot;mp_product_image_link&quot; href=&quot;' . $amazonurl . '&quot;><img src=&quot;' . $amazonurl . '&quot; class=&quot;alignleft mp_product_image_single wp-post-image&quot; width=&quot;175&quot; /></a>';
	  		}

One thing to note is that in my containing post div I had to remove the reference to the post class to fix the slight CSS issue it creates. So remove this from the post div if you have it:
<?php post_class(); ?>
I also hard coded the title on this page too.

IMPORTANT: you will also have to remove the famous WP loop from mp_productlist.php so all the IF WHILE POST stuff should be removed.

OK upload the template file and your functions.php and view your product list page i.e. http://yoururl.com/store/products/
If all has gone well it will display the Amazon images here too, wicked.

Now take a big gulp of whisky as we are done.

So what we have done here is add the ability to easily use Amazon product images for your featured product images but keeping the ability to add your own featured images.

I will re-visit this tut as I do more on my own site and post any new templates etc. I may integrate a grid view for the product list too.

Any queries, bug reports or improvements to my code gratefully received.

Cheers

**Edit
Ive now made an mp_category.php template file, this is almost exactly the same as mp_productlist.php but for one line. I found this in the WP codex and its great for displaying the actual page name, as I found with this particlular template it would display the first product name instead of the page name. Here is the code to solve that particluar issue:

<h2 class="pagetitle"><?php single_cat_title('Category: '); ?></h2>

  • ThePath

    Thanks guys. WP may allow the use of URL fetched featured images in 3.5 so people may not want to use this tut however Im sure there are some advantages to seperating them out as I have done.

    I was working on it more last night and Id like to add a bit to the tutorial. What I wanted to do was to link the image to the external URL. Thats the field in your product admin that overwrites the buy button (where you put your Amazon link). At first I thought about trying to obtain the variable from one of the MP functions and then thought hey wait a minute WP has built in functions so I dont need to code, and hey presto to retrieve the external url in MP one just has to:

    $amazonlink = get_post_meta($post->ID, 'mp_product_link', true);

    Then you can use the $amazonlink variable anywhere you want i.e. in the image link:

    <a id="product_image-<?php the_ID(); ?>" class="mp_product_image_link" href="<?php echo $amazonlink; ?>">

    So I changed the two template files. But rather than post the code (which by the way is displayed a bit rubbishly on this forum....can we not have syntax highlighting?) I'll just upload the two template files.

    Cheers

  • ThePath

    Updated Tut:

    Hi WPMU Devers,

    OK so I promised Mason and James that I would start adding useful stuff to the forum. So this is my first addition and a wee tutorial to help those wishing for a better way to display Amazon products via MP.

    First off what do I mean by "integrating", well I mean using the image from Amazon as your featured image. Currently in WP there is no way to show an image fetched from another site i.e. Amazon as your featured image. Perhaps its coming in 3.5 which will make this tut reduntant pretty quickly....ah well.

    What you will need:
    1. Marketpress plugin installed....duh
    2. Custompress plugin installed
    3. Code editor program (I use Dreamweaver)
    4. You need to be an Amazon affiliate
    5. A whisky (Single Malt, possibly Speyside and finished in a sherry cask...optional)

    OK so Im assuming you already have MP with some test products and custompress installed and working correctly.

    Create your custom field
    Click on Content Types under the Custompress menu (note this is in your network admin panel if you have multisite installed). Then click on the Custom Fields tab and the Add Custom Field button. (see first screenshot)

    Fill out the title field I chose "Amazon Image". Under Post Type make sure and select; Product! Add the custom field via blue button and that will add a new custom field to the add/edit Product page (see screensot 2), put the image url from your amazon affiliate product here. Well done, now take a sip of whisky.

    Using your new custom field to display a featured image from a URL
    OK so at this point we need to use this custom field in our custom MP template. If you dont know how to make a custom MP template then get reading Themeing_MarketPress.txt found in marketpress/marketpress-includes/themes

    The two templates Ive made so far are:

    mp_product.php
    mp_productlist.php

    Im sure that other templates and perhaps widgets which will also require tweaking but I havent done this yet and if there is then the principles will be the same as the two above.

    So lets do mp_product.php first, not ready? OK take a sip of whisky.

    I'll just dump all the code within my post div and then explain it:

    <div class=&quot;entry&quot;>
    						<?php
    						$amazonurl = get_post_meta($post->ID, '_ct_text_507991f6b6920', true);
    						if ( $amazonurl == &quot;&quot;) {
    							mp_product_image(true, 'single', null);
    						} else { ?>
                                <a id=&quot;product_image-<?php the_ID(); ?>&quot; class=&quot;mp_product_image_link&quot; href=&quot;<?php echo $amazonurl; ?>&quot;><img src=&quot;<?php echo $amazonurl; ?>&quot; class=&quot;alignleft mp_product_image_single wp-post-image&quot; width=&quot;175&quot; /></a>
                            <?php } ?>
    
                            <?php the_content(); ?>
                            <div class=&quot;mp_product_meta&quot;>
    							<?php  mp_product_price();
                                //button
                                mp_buy_button(true, 'single', null);?>
                            </div>
                            <?php echo mp_category_list($product_id, '<div class=&quot;mp_product_categories&quot;>' . __( 'Categorised in ', 'mp' ), ', ', '</div>'); ?>
                            <?php echo mp_tag_list($product_id, '<div class=&quot;mp_product_tags&quot;>', ', ', '</div>'); ?>
    					</div>

    Right so we need to add the contents of our custom field to a variable for ease of use. To do this go back to the Custom Press->Content Types admin page, there you will see the new field you created, hover over it and select the Embed Code link. This gives you the shortcode with custom field key we need prefixed by "id=" (see screenshot 3). Replace my key from line 1 with yours i.e.
    $amazonurl = get_post_meta($post->ID, 'YOUR KEY HERE', true);
    Ok so we now have an URL from the custom field stored in the $amazonurl variable. Now we just have to stick it in an <img> tag right? Well yes but we also want the ability to add our own products and so use the native WP featured image function. So Ive added a conditional IF statement which will use the native WP featured image if $amazonurl is emtpy.

    Ive used a width of 175px in the <img> tag so change this to suit your theme, the height should adjust automagically.

    Then we display the product content, price, buy button, category list and tag list. You will notice rather than mess about with shortcodes Im just linking in to the actual functions from template-functions.php feel free to use the shortcodes if your more comfy with them.

    Upload that and visit your test product page. Woohoo the product page displays the Amazon image! Ahhhhh sip of whisky.

    OK lets do the main product list now which was a bit more of a challenge. This is your mp_productlist.php file. So to list the products we would link into the mp_list_products in template-functions.php but wait that would just spew out the products with the featured image and not have our nice conditional statement that we used earlier. Damn, better take a sip of whisky. OK no problem all we have to do is copy the whole mp_list_products function over to your themes functions.php and rename it, I called mine thepath_list_products and I will dump the code again and review the necessary changes:

    function thepath_list_products( $echo = true, $paginate = '', $page = '', $per_page = '', $order_by = '', $order = '', $category = '', $tag = '' ) {
      global $wp_query, $mp;
    
      //setup taxonomy if applicable
      if ($category) {
        $taxonomy_query = '&product_category=' . sanitize_title($category);
      } else if ($tag) {
        $taxonomy_query = '&product_tag=' . sanitize_title($tag);
      } else if (isset($wp_query->query_vars['taxonomy']) && ($wp_query->query_vars['taxonomy'] == 'product_category' || $wp_query->query_vars['taxonomy'] == 'product_tag')) {
        $term = get_queried_object(); //must do this for number tags
        $taxonomy_query = '&' . $term->taxonomy . '=' . $term->slug;
      } else {
        $taxonomy_query = '';
      }
    
      //setup pagination
      $paged = false;
      if ($paginate) {
        $paged = true;
      } else if ($paginate === '') {
        if ($mp->get_setting('paginate'))
          $paged = true;
        else
          $paginate_query = '&nopaging=true';
      } else {
        $paginate_query = '&nopaging=true';
      }
    
      //get page details
      if ($paged) {
        //figure out perpage
        if (intval($per_page)) {
          $paginate_query = '&posts_per_page='.intval($per_page);
        } else {
          $paginate_query = '&posts_per_page='.$mp->get_setting('per_page');
    		}
    
        //figure out page
        if ($wp_query->query_vars['paged'])
          $paginate_query .= '&paged='.intval($wp_query->query_vars['paged']);
    
        if (intval($page))
          $paginate_query .= '&paged='.intval($page);
        else if ($wp_query->query_vars['paged'])
          $paginate_query .= '&paged='.intval($wp_query->query_vars['paged']);
      }
    
      //get order by
      if (!$order_by) {
        if ($mp->get_setting('order_by') == 'price')
          $order_by_query = '&meta_key=mp_price_sort&orderby=meta_value_num';
        else if ($mp->get_setting('order_by') == 'sales')
          $order_by_query = '&meta_key=mp_sales_count&orderby=meta_value_num';
        else
          $order_by_query = '&orderby='.$mp->get_setting('order_by');
      } else {
      	if ('price' == $order_by)
      		$order_by_query = '&meta_key=mp_price_sort&orderby=meta_value_num';
        else
        	$order_by_query = '&orderby='.$order_by;
      }
    
      //get order direction
      if (!$order) {
        $order_query = '&order='.$mp->get_setting('order');
      } else {
        $order_query = '&order='.$order;
      }
    
      //The Query
      $custom_query = new WP_Query('post_type=product&post_status=publish' . $taxonomy_query . $paginate_query . $order_by_query . $order_query);
    
      //allows pagination links to work get_posts_nav_link()
      if ($wp_query->max_num_pages == 0 || $taxonomy_query)
        $wp_query->max_num_pages = $custom_query->max_num_pages;
    
      $content = '<div id=&quot;mp_product_list&quot;>';
    
      if ($last = $custom_query->post_count) {
        $count = 1;
        foreach ($custom_query->posts as $post) {
    
    			//add last css class for styling grids
    			if ($count == $last)
    			  $class = array('mp_product', 'last-product');
    			else
    			  $class = 'mp_product';
    
          $content .= '<div '.mp_product_class(false, $class, $post->ID).'>';
          $content .= '<h3 class=&quot;mp_product_name&quot;><a href=&quot;' . get_permalink( $post->ID ) . '&quot;>' . $post->post_title . '</a></h3>';
          $content .= '<div class=&quot;mp_product_content&quot;>';
    	  $amazonurl = get_post_meta($post->ID, '_ct_text_507991f6b6920', true);
    			if ( $amazonurl == &quot;&quot;) {
    				$product_content = mp_product_image( false, 'list', $post->ID );
    			} else {
    				$product_content = '<a id=&quot;product_image-' . $post->ID . '&quot; class=&quot;mp_product_image_link&quot; href=&quot;' . $amazonurl . '&quot;><img src=&quot;' . $amazonurl . '&quot; class=&quot;alignleft mp_product_image_single wp-post-image&quot; width=&quot;175&quot; /></a>';
    	  		} 
    
          if ($mp->get_setting('show_excerpt'))
            $product_content .= $mp->product_excerpt($post->post_excerpt, $post->post_content, $post->ID);
          $content .= apply_filters( 'mp_product_list_content', $product_content, $post->ID );
          $content .= '</div>';
    
          $content .= '<div class=&quot;mp_product_meta&quot;>';
          //price
          $meta = mp_product_price(false, $post->ID);
          //button
          $meta .= mp_buy_button(false, 'list', $post->ID);
          $content .= apply_filters( 'mp_product_list_meta', $meta, $post->ID );
          $content .= '</div>';
    
          $content .= '</div>';
    
          $count++;
        }
      } else {
        $content .= '<div id=&quot;mp_no_products&quot;>' . apply_filters( 'mp_product_list_none', __('No Products', 'mp') ) . '</div>';
      }
    
      $content .= '</div>';
    
      if ($echo)
        echo $content;
      else
        return $content;
    }

    Basically the changes Ive made are really taking the hard work we did in mp_product.php and convert it into the right syntax to use in the new function. So this section:

    $amazonurl = get_post_meta($post->ID, '_ct_text_507991f6b6920', true);
    			if ( $amazonurl == &quot;&quot;) {
    				$product_content = mp_product_image( false, 'list', $post->ID );
    			} else {
    				$product_content = '<a id=&quot;product_image-' . $post->ID . '&quot; class=&quot;mp_product_image_link&quot; href=&quot;' . $amazonurl . '&quot;><img src=&quot;' . $amazonurl . '&quot; class=&quot;alignleft mp_product_image_single wp-post-image&quot; width=&quot;175&quot; /></a>';
    	  		}

    One thing to note is that in my containing post div I had to remove the reference to the post class to fix the slight CSS issue it creates. So remove this from the post div if you have it:
    <?php post_class(); ?>
    I also hard coded the title on this page too.

    IMPORTANT: you will also have to remove the famous WP loop from mp_productlist.php so all the IF WHILE POST stuff should be removed.

    OK upload the template file and your functions.php and view your product list page i.e. http://yoururl.com/store/products/
    If all has gone well it will display the Amazon images here too, wicked.

    Now take a big gulp of whisky as we are done.

    So what we have done here is add the ability to easily use Amazon product images for your featured product images but keeping the ability to add your own featured images.

    I will re-visit this tut as I do more on my own site and post any new templates etc. I may integrate a grid view for the product list too.

    Any queries, bug reports or improvements to my code gratefully received.

    Cheers

    **Edit
    Ive now made an mp_category.php template file, this is almost exactly the same as mp_productlist.php but for one line. I found this in the WP codex and its great for displaying the actual page name, as I found with this particlular template it would display the first product name instead of the page name. Here is the code to solve that particluar issue:

    <h2 class="pagetitle"><?php single_cat_title('Category: '); ?></h2>