Magento 2:カスタム属性をカタログに表示する方法


13

次の設定をyesに設定して、新しいtextfield属性を作成しました。

Visible on Catalog Pages on Storefront
Used in Product Listing

属性が属性セットに割り当てられ、意図したとおりに製品ビューに表示されます。

ただし、カタログビューには表示されません。デフォルトのLumaテーマを使用しており、キャッシュをクリアしてインデックスを再作成しました。テンプレートファイルを表示した場合:

magento-catalog/view/frontend/templates/product/list.phtml

カスタム属性を取得するコードが見つからないため、Lumaテーマはデフォルトでこれをサポートしていないようです。

list.phtmlで製品のカスタム属性ラベルと値を取得するにはどうすればよいですか?

回答:


22

以下のようなカスタム属性値を取得できます

属性値

<?php /* @escapeNotVerified */ echo $_product->getResource()->getAttribute('c_address')->getFrontend()->getValue($_product); ?>

ラベル

$address =$_product->getResource()->getAttribute('c_address')->getStoreLabel();

注:上記の行のc_addressは、私のカスタム属性コードです。

参照: Magento/Catalog/templates/product/view/attribute.phtml


属性がmedia imageタイプの場合は機能しません。
LucScu 2017年

@Bilal、私にとってカスタム属性はlist.phtmlで「致命的なエラーgetFrontend」を示しています。あなたが任意のアイデアがあれば、あなたは、このエラーを回避する方法をしてくださいしてください伝えることができます
Hitesh Balpande

11

私はこれに関する記事を作成しました。それを行うための5つのステップしかありません。

1- Stores> Attributes> Productで属性を作成します。

2-[デフォルト]グループに属性を設定し、[ストア]> [属性]> [属性セット]に移動します。

3-製品にこの属性の値を設定します。

4-以下の相対ファイルをカスタムテーマで開きます。

app/design/frontend/CUSTOM/THEME/Magento_Catalog/templates/product/list.phtml

5-foreach関数の間に以下のコードを貼り付けますが、正しい属性のコードを変更します。

$_getMyAttr = $_product->getResource()->getAttribute('my_attribute');

if ($_getMyAttr){

    // Get Value
    $attrTestValue = $_getMyAttr->getFrontend()->getValue($_product);

    // Get Label
    $attrTestLabel = $_getMyAttr->getStoreLabel();
}

重要

ていることを確認し、「製品ビューフロントエンド上のページに表示」「商品リストに使用される」店頭のプロパティの下のオプションがYesに設定されています。

リファレンス:https : //rafaelstz.github.io/magento/magento2-display-custom-attribute-catalog-list-products.html


ではmedia image、「商品リストに使用さ」と「フロントエンドの製品表示ページに表示」属性に設定可能ではありません。
LucScu

価格属性についても同様
CompactCode

デフォルトのlist.phtmlはどこにありますか?
mikebertiean

こんにちは、属性ラベルは機能しますが属性値は機能しません
Sarvesh Tiwari '29

6

これを使って

$attribute = $_product->getResource()->getAttribute('identifier'); 
if ($attribute) 
{ 
$attr_value = $attribute ->getFrontend()->getValue($_product); 
}

1

@mikebertieanデフォルトのlist.phtmlに移動するには

<Magento base>/vendor/magento/module-catalog/view/frontend/templates/product

それをコピーして変更し、Rafaelが言及したパスに追加したら、キャッシュをフラッシュするだけで動作します。


0

開いた

app/design/frontend/CUSTOM/THEME/Magento_Catalog/templates/product/list.phtml

次のforeachループを追加します。

<?php

$brand_attribute = $_product->getResource()->getAttribute('brand');

if ($brand_attribute){

    // Get Value
    $brand_value = $brand_attribute->getFrontend()->getValue($_product);

    // Get Label
    $brand_lable = $brand_attribute->getStoreLabel();
    echo $brand_lable." : ".$brand_value;
}

?>
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.