How to create add to compare in WordPress?

I don’t want to use any plugin. I tried creating compare page using cookie but still got problem. Can anyone please let me know that how I can create Compare products in wordpress?

Using Loop I get following output where I added “add to compare” Link or button

Read More
<table>
<tr>
  <td> Product ID</td>
  <td>Product Name</td>
  <td><a href="#">Add To Compare</a></td>
</tr>
<tr>
  <td> 123</td>
  <td>P-one</td>
  <td><a href="#">Add To Compare</a></td>  
</tr>
<tr>
  <td>234</td>
  <td>P-2</td>
  <td><a href="#">Add To Compare</a></td>
</tr>
<tr>
  <td>345</td>
  <td>P-3</td>
  <td><a href="#">Add To Compare</a></td>
</tr>
<tr>
  <td>456</td>
  <td>P-4</td>
  <td><a href="#">Add To Compare</a></td>
</tr>
  </table>

My logic is not clear. I dont know what should I do to build add to compare product page. But I tried following steps to create compare product page:


I have created two custom post types:

  1. Main Product
  2. Sub Product

Main Products are the Parent Posts of Sub Products. That means Sub Products are the child of Main Products.

Main products are the posts for brands and Sub Products are the posts where we add products and their details related to these brands.

I have a brand called BARATA (assume :P) and their Products are:

  1. Barata Pone
  2. Barata Ptwo
  3. Barata Pthree
  4. Barata Pfour

They all have same specification like WIDTH, LENGTH, HEIGHT.

In Main Product custom template I added this loop to get its child posts from sub products

<table>
            <thead>
                <tr>
                    <th><h4>Product Name</h4></th>
                    <th><h4>Any Info</h4></th>
                    <th><h4>Select to Compare</h4></th>

                </tr>
            </thead>
            <tbody>
<?php
$childargs = array(


'orderby' => 'post_title',
'order' => 'ASC',
);
$compi = 1;
 $child_posts = types_child_posts("subproducts",$childargs);
foreach ($child_posts as $child_post) {  

$variid = $child_post->ID;
$variname = "compareid".$compi++;
?>


            <tr>
                    <td><?php echo $child_post->post_title; ?></td>
                    <td><?php echo get_post_meta($child_post->ID, 'any-info-cutomfield', TRUE);  ?></td>
                    <th><a href="" onclick="setting_my_first_cookie('<?php echo $variid; ?>','<?php echo $variname; ?>')">Compare</a>

<a href="" onclick="setting_my_first_cookie_delete('<?php echo $variid; ?>','<?php echo $variname; ?>')">Remove</a>
</th>

                </tr>
            </tbody>
<?php
// Accessing an individual cookie value
echo $_COOKIE[$variid];
echo $_COOKIE[$variname];

?>

  <?php 
} 

?>

Above code fetches child products of the main page and shows them in table with Add to compare buton. in $variid I store the ID of child products and Their name $variname.

Using Onclick I send these data to the javascript function to create cookies.

Javascript:

<script type="text/javascript"> 

function setting_my_first_cookie(variid,variname) {
 var d = new Date();
    d.setTime(d.getTime() + (30*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = variname + "=" + variid + "; " + "expires; path=/; domain=.domain.com";
}
</script>

<script type="text/javascript"> 

function setting_my_first_cookie_delete(variid,variname) {
   document.cookie = variname + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/; domain=.domain.com';
}
</script>

on Comparison page I can retrieve these data to show comparison of these products. but there are some problems. Like I don’t know how to add limit for products to be compare.

Can you give me logic to add products to compare. How others do it actually? How I can do it? Please guide me to the right direction.

Related posts

2 comments

  1. You could use you $_SESSION which might be a cleaner way of handling the logic. functions to add / remove items would be the following (untested code):

    $_SESSION['barata_products'] = [];
    
    function add_products(varid) {
        array_push($_SESSION['barata_products'],varid);
    }
    
    function remove_product(varid) {
        $product_index = array_search(varid,$_SESSION['barata_products']);
        unset($_SESSION['barata_products'][$product_index]);
    }
    
    function remove_all_products() {
        $_SESSION['barata_products'] = [];
    }
    
    //helper function to check if the session array is greater than your desired amount, where x is number of products within the array.
    function more_than_x(session,x) {
        $_SESSION['barata_products'].count() > x ? true : false
    }
    

    If you need fancier logic with wordpress sessions, check out this blog

  2. You can simply use ajax to create a session for each product like :

    $(document).ready(function(){
      $('.product').click(function(){
        var product_id = $(this).attr('id');
         $.ajax({
         method: 'POST',
         url : "YOUR PHP FILE NAME",
         data : {product_id:product_id},
         success : function(resp){
         alert("Product is added to be compared");
         }
         });
      });
    });
    

    PHP FILE CODE :

     <?php 
      session_start();
      $product_id = $_POST['product_id'];
      if(!is_array($_SESSION['ids']))
      {
       $_SESSION['ids'] = array();
      }
      else
      {
        array_push($_SESSION['ids'], $product_id);
      }
     ?>
    

    Then you can use that $_SESSION variable to get all the product ids to your compare template.

Comments are closed.