在单个产品页面上显示产品属性字段

问题描述 投票:0回答:1

我创建了一个字段来添加到 WooCommerce 属性中。我在下面添加了一张图片以获得更多间隙。

我正在尝试在单个产品页面上显示该字段。我已将以下代码添加到 content-single-product.php 模板文件中。

$terms = get_the_terms( $product->id, 'pa_merk');
var_dump($terms);

$image = get_field('afbeelding_merk', $terms->taxonomy . '_' . $terms->slug);

// Display the image if it exists
if ($image) {
    echo '<img src="' . $image . '" />';
} else {
    echo "<p>Foto niet gevonden.</p>";
}

我做错了什么?

我尝试了多种方法来检索术语分类法和slug。但在很多方面它都说 NULL。我尝试在互联网上搜索并询问chatgpt。我还尝试将“$terms->slug”部分更改为“$terms->term_id”,但这也没有帮助。

php wordpress woocommerce advanced-custom-fields acfpro
1个回答
0
投票

您的代码中有错误。请尝试以下方法:

$product_id = $product->get_id(); // get the product ID
$taxonomy   = 'pa_merk';
$terms      = wp_get_post_terms( $product_id, $taxonomy ); // get the product terms

if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
    $term = reset($terms); // get the first WP_Term object

    $image = get_field('afbeelding_merk', $taxonomy . '_' . $term->slug);

    // Display the image if it exists
    if ( ! empty($image) ) {
        echo '<img src="' . $image . '" />';
    } else {
        echo "<p>Foto niet gevonden.</p>";
    }
} else {
    echo "<p>Foto niet gevonden.</p>";
}

应该可以。

© www.soinside.com 2019 - 2024. All rights reserved.