0

我希望能够为每个产品显示特定的添加到卡片文本(如果已设置)。

那里有一些插件,但它们“只是”涵盖类别或产品类型的添加到卡片文本。这就是我使用自定义字段尝试这种方式的原因。

所以我直接在模板文件中编写了这段代码。此代码有效,但它在正确的位置是否良好、安全?

// file: /woocommerce-templates/single-product/add-to-cart/simple.php
<button "..." >
    <?php
        $text = get_post_meta($product->get_id(), 'add_to_cart_text', true);
    if ($text) {
        echo esc_html($text);
    } else {
        echo esc_html($product->single_add_to_cart_text()); // this line is default
    }
    ?>
</button>
4

1 回答 1

2

我会改用这个:

<?php
add_filter( 'woocommerce_product_add_to_cart_text', 'custom_add_to_cart_button_text', 20, 2 );
function custom_add_to_cart_button_text( $button_text, $product ) {
    $custom_button_text = get_post_meta( $product->get_id(), 'add_to_cart_text', true );

    // If there is custom text set for this product, then display it instead of the default text.
    if ( ! empty( $custom_button_text ) ) {
        $button_text = __( $custom_button_text, 'text-domain' );
    }

    return $button_text;
}

将其粘贴到您的functions.php中

于 2019-02-13T18:18:25.727 回答