magento2.4.1 – Load Products by SKU in Custom Widget

I am building a custom widget that I want to display specific products based on the product SKU. I have tried a few different code examples to get products using the dependency injection method, but when I try to get the product name, it errs.

Error: Call to a member function getName() on null

The products I am trying to get are all enabled and exist in the database, so I don’t see any reason for it to not be able to get the name.

Not sure what exactly I’m missing …

These are the tutorials I have looked at:

Magento 2: Get product by SKU or ID

How to Load Products by Product ID and SKU in Magento 2?

Magento 2 – How to Get Product by SKU


<?xml version="1.0" ?>
<widgets xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Widget:etc/widget.xsd">
<widget class="VendorModuleBlockWidgetFeaturedproducts" id="vendor_module_featuredproducts">
    <label>Featured Products</label>
    <description>Enter SKUs for products to feature</description>
        <parameter name="featuredproductsid" sort_order="10" visible="true" xsi:type="text">
            <label>SKUs (comma separated)</label>


namespace VendorModuleBlockWidget;

use MagentoFrameworkViewElementTemplate;
use MagentoWidgetBlockBlockInterface;

class Featuredproducts extends Template implements BlockInterface
    protected $_template = "widget/featuredproducts.phtml";


  namespace VendorModuleBlock;

 class Widgets extends MagentoFrameworkViewElementTemplate
  public $_productRepository;
public function __construct(
    MagentoBackendBlockTemplateContext $context,       
    MagentoCatalogModelProductRepository $productRepository,
    array $data = ()
    $this->_productRepository = $productRepository;
    parent::__construct($context, $data);

public function getProductById($id)
    return $this->_productRepository->getById($id);

public function getProductBySku($sku)
    return $this->_productRepository->get($sku);


<?php if($block->getData('featuredproductsid')): 

  $featuredSkus = $block->getData('featuredproductsid'); 
  $arr_featuredSkus = explode(',', $featuredSkus);?>

 <div class="featured-products-rotator">
   <?php foreach($arr_featuredSkus as $sku) { 

    $prod = $block->getProductDataUsingSku($sku); ?>

    <a href="#" class="product-content">
      <span class="headline"><?php echo $prod->getName(); ?></span>

  <?php } ?>
<?php endif; ?>

When I use the ObjectManager method, each of the items list as expected.

$product = MagentoFrameworkAppObjectManager::getInstance()
        ->loadByAttribute('sku', $sku);