简体   繁体   中英

PrestaShop 1.7 - search products by tag

I noticed that in PrestaShop 1.7 you can tag products. Is it possible to search for products by their tags programmatically?

So for example if I wanted to find products which contain any of the ['madcow, crazydog, happyant'] tags, how do I approach it?

$this->context->getProducts('tag', ['madcow, crazydog, happyant']) ?

or maybe

Product::getByAttribute('tag', ['madcow, crazydog, happyant'])

or similar?

any help much appreciated

You can get the active products (id and name) foreach tag by doing:

$tag = new Tag(null, "tag", $idlang);
$products = $tag->getProducts();

The tag contructor also So your code could be something like:

$context = \Context::getContext();
$idlang = $context->language->id;

$tags = ['madcow', 'crazydog', 'happyant'];
$products = [];
foreach($tags as $t){
    $tag = new Tag(null, $t, $idlang);
    if($tag != null){
        $tag_products = $tag->getProducts();
        foreach($tag_products as $tg)
            $products[$tg['id_product']] = $tg['name'];
    }
}

EDIT: Taking account the comments, maybe it would be best to get all tags

$context = \Context::getContext();
$idlang = $context->language->id;

$tags = ['madcow', 'crazydog', 'happyant'];
$products = [];
foreach($tags as $t){
    $tag = new Tag(null, $t, $idlang);
    if($tag != null){
        $tag_products = $tag->getProducts();
        foreach($tag_products as $tg) {
            if(!isset($products[$tg['id_product']])) {
                 $products[$tg['id_product']] = [];
            }
            $products[$tg['id_product']][] = $tg['name'];
        }
    }
}

Then if you want to sort by number of tags found, you could do something like:

usort($product, function($a, $b) { return count($b) - count($a); });

Disclaimer: Not tested, please let me know if you find any mistake.

You can use this snippet :

$array_tags = implode(',',['one','two','three']);

$id_lang = $this->context->language->id;

$products = Db::getInstance()->executeS('
    SELECT pl.id_product
    FROM `'._DB_PREFIX_.'product` p
    LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON p.id_product = pl.id_product'.Shop::addSqlRestrictionOnLang('pl').'
    '.Shop::addSqlAssociation('product', 'p').'
    WHERE pl.id_lang = '.(int) $id_lang.'
    AND product_shop.active = 1 
    AND p.id_product IN (SELECT pt.id_product FROM `'._DB_PREFIX_.'product_tag` pt WHERE pt.name IN ('.pSQL($array_tags).'))
    ORDER BY pl.name');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM