使用 ACF 字段更改 WooCommerce 产品简短描述

Alter WooCommerce product short description with an ACF field

我正在尝试在 Woocommerce 中的产品简短描述后添加 ACF WYSIWYG 字段。我将以下内容添加到 functions.php 但它也在类别页面上显示 ACF 字段???

add_filter('woocommerce_short_description','ts_add_text_short_descr');
function ts_add_text_short_descr($description){

if (get_field('extra_short_description')) { 
$extra_desc = get_field( 'extra_short_description' );
return $extra_desc;
}
}

然后我偶然发现了另一个有效的建议代码,但如果产品没有自定义 ACF 字段,那么它就会像缺少 div:

add_action( 'woocommerce_single_product_summary', 'custom_single_product_summary', 2 );
function custom_single_product_summary(){
global $product;
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_excerpt', 20 );
add_action( 'woocommerce_product_meta_start', 'custom_single_excerpt', 20 );
}

function custom_single_excerpt(){
global $post, $product;
$short_description = apply_filters( 'woocommerce_short_description', $post->post_excerpt );
if ( ! $short_description )   
return ;

if (get_field('extra_short_description'))
$extra_desc = get_field( 'extra_short_description' );

?>
<div class="woocommerce-product-details__short-description">
    <?php echo $short_description .$extra_desc; ?>
</div>
<?php
} 

上面的代码缺少什么?

已更新

你的第一个函数代码应该是这样的:

add_filter('woocommerce_short_description','ts_add_text_short_descr');
function ts_add_text_short_descr( $short_description ){
    global $post;
    
    $extra_short_description = get_field( 'extra_short_description' );
    if ( ! empty($extra_short_description) ) {
        $short_description .= $extra_short_description;
    }
    return $short_description;
}

那么你的其他功能应该是这样的:

add_action( 'woocommerce_single_product_summary', 'custom_single_product_summary', 2 );
function custom_single_product_summary(){
    global $product;

    remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_excerpt', 20 );
    add_action( 'woocommerce_single_product_summary', 'custom_single_excerpt', 35 );
}

function custom_single_excerpt(){
    global $post, $product;

    $short_description = apply_filters( 'woocommerce_short_description', $post->post_excerpt );

    $extra_short_description = get_field('extra_short_description');
    if ( ! empty($extra_short_description) ) {
        $short_description .= $extra_short_description;
    }

    if ( ! empty($short_description) ) :
    ?>
    <div class="woocommerce-product-details__short-description">
        <?php echo $short_description; ?>
    </div> <?php
    endif;
} 

它应该更好用。