EC-CUBE4の商品詳細ページで、参照している商品と同じカテゴリに属する商品の一覧を表示する方法をご紹介いたします。おすすめ商品の一覧を表示したい時に活用できます。
EC-CUBE4の商品詳細ページで同じカテゴリの商品一覧を表示する方法
/app/template/テンプレート名/Product/detail.twigの中に、下記を追記します。
{# 現在の商品が属するカテゴリを取得 #}
{% set categories = Product.ProductCategories %}
{% if categories|length > 0 %}
{# 子カテゴリを基準にする #}
{% set targetCategory = null %}
{% for c in categories %}
{% if targetCategory is null and c.Category.Parent is not null %}
{% set targetCategory = c.Category %}
{% endif %}
{% endfor %}
{# 子カテゴリが見つからない場合は先頭カテゴリを基準にする #}
{% if targetCategory is null %}
{% set targetCategory = categories[0].Category %}
{% endif %}
{# 同カテゴリの商品を取得(自身を除外) #}
{% set RecommendList = repository('Eccube\\Entity\\Product').createQueryBuilder('p')
.innerJoin('p.ProductCategories', 'pc')
.where('pc.Category = :cat')
.andWhere('p.id != :currentId')
.setParameter('cat', targetCategory.id)
.setParameter('currentId', Product.id)
.setMaxResults(5)
.getQuery()
.getResult()
%}
{% if RecommendList|length > 0 %}
<ul>
{% for Rec in RecommendList %}
<li>
<a href="{{ url('product_detail', {'id': Rec.id}) }}">
<figure class="recommend-img">
{% if Rec.ProductImage|length > 0 %}
<img src="{{ asset(Rec.ProductImage[0], 'save_image') }}" alt="{{ Rec.name }}">
{% else %}
<img src="{{ asset(''|no_image_product, 'save_image') }}" alt="{{ Rec.name }}">
{% endif %}
</figure>
<h2 class="recommend-name">{{ Rec.name }}</h2>
<div class="recommend-price-regular">
{% if Rec.hasProductClass -%}
{% if Rec.getPrice01Min is not null and Rec.getPrice01IncTaxMin == Rec.getPrice01IncTaxMax %}
<span>通常価格:{{ Rec.getPrice01IncTaxMin|price }}</span>
{% elseif Rec.getPrice01Min is not null and Rec.getPrice01Max is not null %}
<span>通常価格:{{ Rec.getPrice01IncTaxMin|price }} ~ {{ Rec.getPrice01IncTaxMax|price }}</span>
{% endif %}
{% else %}
{% if Rec.getPrice01Max is not null %}
<span>通常価格:{{ Rec.getPrice01IncTaxMin|price }}</span>
{% endif %}
{% endif %}
</div>
<div class="recommend-price-sale">
{% if Rec.hasProductClass -%}
{% if Rec.getPrice02IncTaxMin == Rec.getPrice02IncTaxMax %}
<span>販売価格:{{ Rec.getPrice02IncTaxMin|price }}</span>
{% else %}
<span>販売価格:{{ Rec.getPrice02IncTaxMin|price }} ~ {{ Rec.getPrice02IncTaxMax|price }}</span>
{% endif %}
{% else %}
<span>販売価格:{{ Rec.getPrice02IncTaxMin|price }}</span>
{% endif %}
</div>
</a>
</li>
{% endfor %}
</ul>
{% endif %}
{% endif %}参照中の商品は一覧から除外されるようにしています。
参照している商品のカテゴリから基準となるカテゴリを取得するのですが、親カテゴリを基準にすると含めたくない商品もヒットしてしまう可能性があるので、子カテゴリを基準とするようにしています。子カテゴリがない場合は、最初のカテゴリを基準にします(親カテゴリであっても)。
「setMaxResults(5)」の箇所が取得件数です。上記の場合、最大5件の商品が表示されます。
あとがき
“おすすめ商品管理プラグイン”という無料のプラグインもありますが、手動でおすすめ商品を追加/削除して管理するタイプです。Twigコードのカスタマイズが難しい場合は、プラグインを利用する方が良いですね。
商品一覧の表示を自動化したい時は、上述したコードを自サイトに合わせて改変して実装する方が柔軟に対応できて良いかと思います。

