首页 > 解决方案 > 在 WooCommerce 存档页面中的产品标题下方显示 ACF 字段/图像

问题描述

我正在使用高级自定义字段插件,我可以在存档页面上的产品标题下方显示文本字段,但我还需要在同一位置(在文本字段下)显示图像作为徽标。

这是我用于显示文本字段的代码,它可以工作;

add_action( 'woocommerce_after_shop_loop_item_title', 'custom_field_display_below_title', 2 );
function custom_field_display_below_title(){
    global $product;

    // Get the custom field value
    $custom_field = get_post_meta( $product->get_id(), 'oa1', true );

    // Display
    if( ! empty($custom_field) ){
        echo '<p class="ozel-alanlar">'.$custom_field.'</p>';
    }

}

而且我还尝试使用此代码显示图像字段,但它不起作用;

add_action( 'woocommerce_after_shop_loop_item_title', 'custom_image_display_below_title', 2 );
function custom_image_display_below_title() {
    global $product;

    // Get the custom field value
    $oa2 = get_post_meta( $product->id, 'oa2', true );

    // Display
    if ( ! empty( $oa2 ) ) {
        echo '<img src="' . $oa2 . '" />';
    }

}

这就是结果;

http://www.awesomescreenshot.com/image/3601047/62187bf2b14fc220112fc9456bda1ec9

以及我创建的自定义字段;

http://www.awesomescreenshot.com/image/3601051/9559df786631f1dc4d81937487e6bba2

http://www.awesomescreenshot.com/image/3601052/202b5f9b0f05aa661e16ece303ab7abe

如果有人可以帮助我,我将不胜感激。,

此致。

标签: phpwordpresswoocommerceadvanced-custom-fieldsimagefield

解决方案


当您使用高级自定义字段时,您需要使用get_field()专用功能。图片字段需要设置为“图片网址”。现在代码将是:

add_action( 'woocommerce_after_shop_loop_item_title', 'custom_field_display_below_title', 2 );
function custom_field_display_below_title(){
    global $product;

    // Display ACF text
    if( $text = get_field( 'oa1', $product->get_id() ) ) {
        echo '<p class="ozel-alanlar">' . $text . '</p>';
    }

    // Display ACF image
    if( $image_url = get_field( 'oa2', $product->get_id() ) ) {
        echo '<img src="' . $image_url . '" />';
    }
}

代码位于您的活动子主题(或活动主题)的 function.php 文件中。测试和工作。

你会得到类似的东西:

在此处输入图像描述

ACF 图像字段文档


推荐阅读