在 WooCommerce 内容小部件中的产品标题后立即显示 ACF 自定义字段

Display ACF custom field right after the product title in WooCommerce content widget

我想在最近查看的产品的 WooCommerce 小部件的产品标题下显示一个使用 ACF 生成的自定义字段。

我已经实现了在小部件中回显自定义字段,但它根据操作挂钩显示在产品图片上方 woocommerce_widget_product_item_start 或价格和交货信息下方 woocommerce_widget_product_item_end

我在 functions.php

中使用了以下代码片段
add_action( 'woocommerce_widget_product_item_start', 'acf_field_woo', 6 );
    global $product;
function acf_field_woo() { 
   echo '<p class="wc-subtitle">' . get_field('subtitle') . '<br /></p>';
}

有了它,它就会显示在小部件中产品图片的上方。到目前为止还不错,但是

如何实现在widget中直接显示在产品标题下?

要在产品标题正下方显示您的 ACF 字段,您需要编辑模板文件。可以在 templates/content-widget-product.php

中找到
  • 可以通过将其复制到 yourtheme/woocommerce/content-widget-product.php
  • 来覆盖此模板

所以替换

<a href="<?php echo esc_url( $product->get_permalink() ); ?>">
    <?php echo $product->get_image(); // PHPCS:Ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
    <span class="product-title"><?php echo wp_kses_post( $product->get_name() ); ?></span>
</a>

<a href="<?php echo esc_url( $product->get_permalink() ); ?>">
    <?php echo $product->get_image(); // PHPCS:Ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
    <span class="product-title"><?php echo wp_kses_post( $product->get_name() ); ?></span>
    <?php 
    $subtitle = get_field( "subtitle" );

    if( $subtitle ) {
        echo '<p class="wc-subtitle">' . $subtitle . '</p>';
    }
    ?>
</a>