How to create add to compare in Wordpress?
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
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.