首页 > 解决方案 > 使用 ACF 字段更改 WooCommerce 产品简短描述

问题描述

我试图在 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
} 

任何想法我在上面的代码中缺少什么?

标签: phpwoocommerceproductadvanced-custom-fieldshook-woocommerce

解决方案


更新

您的第一个功能代码应该是这样的:

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;
} 

它应该更好地工作。


推荐阅读