Jump to content

How to get category of product using js


CPTBombaxx

Recommended Posts

Hey,

i need to display something on product using js but i want to display it only on products that are in specific category (is not their main category!) . In tpl i use 

if in_array(2304,Product::getProductCategories($product->id|intval)) 

but I don't know how to do this kind of thing in js. 

Link to comment
Share on other sites

Hi.

In your module, you sent a list of products as an array to your javascript.

$categories = [5, 18, 24];
$categoriesFind = implode(',', $categories);
$products = [];
$findProducts = Db::getInstance()->executeS('SELECT id_product FROM '._DB_PREFIX_.'category_product WHERE id_category IN ('.$categoriesFind.') GROUP BY id_product');

if ($findProducts) {
	foreach ($findProducts as $id_product) {
		$products[] = $id_product['id_product'];
	}
}

$jsDef = ['myCategories' => $categories, 'myProducts' => $products];
Media::addJsDef($jsDef);

 

javascript eg:

$(document).ready(function(){
	var getCategories = myCategories; // array
	var getProducts = myProducts; // array
	var currentProduct = document.getElementById('id_product').value; // change to your element in TPL

	getProducts.forEach(r => { 
		if (currentProduct.includes(r)) { // Ok, found
			// call your function
			okAddMyScript(currentProduct);
		} 
	});
});

function okAddMyScript(e){
	var id_product = e;  
  	// your function
}

 

 

or add module hookHeader, or you custom hook and call it on the applicable product page.

Edited by 4you.software (see edit history)
  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...