在WooCommerce钩子中显示高级自定义字段(ACF)值


Displaying Advanced Custom Field (ACF) value in a WooCommerce hook

我想显示Woocommerce中高级自定义字段(ACF)的值,我正在此函数中钩住以下代码:

add_action( 'woocommerce_single_product_summary', 'charting', 20 );
function charting() {
    if( get_field('size_chart') ) { 
       echo '<p><a href="'.the_field('size_chart').'" data-rel="prettyPhoto">size guide</a></p>';
    }
    return;
}

但它不起作用,它在 href(大小指南)上方显示自定义字段值,并且 href 是空的,如下所示:

<a href="" data-rel="prettyPhoto">size guide</a>

你的问题是你不能将echo与ACF the_field('my_field')一起使用,因为使用the_field('my_field')就像使用echo get_field('my_field')一样,所以你试图echo一个echo。请在代码中以这种方式get_field('my_field')

add_action( 'woocommerce_single_product_summary', 'charting', 20 );
function charting() {
    if( !empty( get_field('size_chart') ) ) { // if your custom field is not empty…
        echo '<p><a href="' . get_field('size_chart') . '" data-rel="prettyPhoto">size guide</a></p>';
    }
    return;
}

之后,我在您的条件下添加了empty()功能...

您也可以尝试return它而不是echo

    return '<p><a href="' . get_field('size_chart') . '" data-rel="prettyPhoto">size guide</a></p>';

参考:

  • ACF the_field
  • ACF get_field

我使用了这段代码,它在本地运行良好,但是当我在服务器中上传函数文件时,它不起作用,并且出现服务器错误 500,所以我不得不再次删除此代码