0

I'm trying to change the prices of products with a plugin. And it works, basically. The problem is this: i only need to change the price of products that have a specific attribute, not the price of all products. With a plugin, it's easy to add a fixed value to the price of a product, but i can't figure out how to check if the product has that custom attribute. this is the code I'm using:

namespace Frostmage\WBTPDC\Plugin;

class Product
{


    public function afterGetPrice(\Magento\Catalog\Model\Product $subject, $result)
    {

        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $wbtvalue = $objectManager->get('Magento\Framework\App\Config\ScopeConfigInterface')->getValue('wbtpdc/modifier/variable');


        return $result * $wbtvalue;
    }
}

Now... It works for the value I added, but I need to add a check, sort of like this:

if ($subject->getData('has_wbt'))
{
    return $result + ($wbtvalue * $subject->getData(weight));
}

Thing is that $subject is not the right variable to use (I wrote that just to exemplify what I need to do). If I try to use objectManager to create a $current_product variable, it always returns an exception for calling getData on null. If I use $subject, it always returns 0. So this is the problem: How can I change the price only of products that have 'has_wbt' attribute so that it shows on the frontend? I mean, is there a way to have this plugin only act on products that have a specific attribute?

2

Below Code is working for me:

if($subject->hasData('color'))
{                
   return 10;             
} 

Now Go to the Store->Product Attribute->Edit Your Attribute->Storefront Properties->Used in Product Listing->Yes

Then save your attribute.

  • Looks like this checks if the attribute exists, and if it does it returns true for every product, even if they don't have said attribute set to true – Riccardo Ronconi Jan 8 at 9:39
  • @Riccardo Ronconi Please check my edited answer. – Dhairya Shah Jan 8 at 10:55
  • it worked perfectly, thank you! The problem was that, while my custom attribute was used in product listing, weight was not (it never came to my mind) so it always returned 0. You really helped an incredible lot, man, Thank You! – Riccardo Ronconi Jan 8 at 11:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.