How to add related products to blog posts using Metafields

Hello,

I need help in adding related products using metafields in shopify. I already created a metafield definition with the namespace and key of “custom.blog_article_related_product” which I tried to display in blog article page

Here is my code:

{% if blog.metafields.custom.blog_article_related_product %}
<aside class="sidebar">   
<div class="sidebar-section related-products">
  <h5>Related Products</h5>
  <div class="slider-container">
    <div class="slider">
       {% for product in blog.metafields.custom.blog_article_related_product %}
            <div class="slide">
              <a href="{{ product.url }}">
                <img src="{{ product.featured_image }}" alt="{{ product.title }}" />
                <p>{{ product.title }}</p>
                <p>{{ product.price | money }}</p>
              </a>
              <button type="submit" class="add-to-cart" onclick="Shopify.addItemToCart('{{ product.id }}', 1)">Add to cart</button>
            </div>
      {% endfor %} 
    </div>
    <button class="prev">‹</button>
    <button class="next">›</button>
  </div>
</div>
</aside>
{% endif %}

But it is not working. Nothing is displaying meaning nothing is being returned and I can’t spot out why.. I will appreciate your support..

I don’t know if anyone is having the same issue out there, I just solved it so I decided to drop the solution incase anyone wish to use.

SOLUTION:

I replaced

blog.metafields.custom.blog_article_related_product

To:

article.metafields.custom.blog_article_related_product.value

That is the main issue. I also did some optimization, kindly find the complete code below.

{% if article.metafields.custom.blog_article_related_product.value %}
<aside class="sidebar"> 
<div class="sidebar-section related-products">
<h5>Related Products</h5>
<div class="slider-container">
<div class="slider">
{% for product in article.metafields.custom.blog_article_related_product.value %}
<div class="slide">
<a href="{{ product.url }}">
<img src="{{product.images[0] | img_url: '420x420' }}" alt="{{ product.images[0].alt }}" />
<p>{{ product.title }}</p>
<p>{{ product.price | money }}</p>
</a>
<button type="submit" class="add-to-cart" onclick="Shopify.addItemToCart('{{ product.id }}', 1)">Add to cart</button>
</div>
{% endfor %} 
</div>
<button class="prev">‹</button>
<button class="next">›</button>
</div>
</div>
</aside>
{% endif %}

Thank you.