在任何地方为 Woocommerce 产品名称添加前缀/后缀,包括购物车和电子邮件

Tem*_*fif -3 php wordpress cart woocommerce hook-woocommerce

我正在使用 Woocommerce 并且我已经集成了一些自定义字段以允许用户指定我稍后将附加到产品标题的新值。

我正在使用update_post_meta/get_post_meta来保存信息。这部分工作正常。

然后我使用过滤器woocommerce_product_title来更新标题。这个过滤器在使用时工作正常,但在使用时$product->get_title()不会做任何事情,$product->get_name()这不是问题,因为在某些地方我不想附加新信息。

我还使用the_title了产品页面的过滤器。

基本上,我的代码如下所示,return_custom()函数将根据产品 ID 构建新信息。

function update_title($title, $id = null ) {

    $prod=get_post($id);

    if (empty($prod->ID) || strcmp($prod->post_type,'product')!=0 ) {
        return $title;
    }

    return $title.return_custom($id);
}

function update_product_title($title, $product) {

    $id = $product->get_id();

    return $title.return_custom($id);
}

add_filter( 'woocommerce_product_title', 'update_product_title', 9999, 2);

add_filter( 'the_title', 'update_title', 10, 2 );
Run Code Online (Sandbox Code Playgroud)

将产品添加到购物车时会出现问题。使用的名称是默认名称,因此我下面的代码不足以更新购物车中使用的产品名称。通知邮件也是一样。我认为这是合乎逻辑的,因为电子邮件将使用购物车的信息。

我很确定一切都在内部发生,add_to_cart()但我找不到与产品名称相关的任何过滤器/挂钩。

如何确保购物车中使用的名称是好的?除了我已经在使用的过滤器/挂钩之外,为了将我的新信息附加到购物车中的产品标题,我还应该考虑哪些过滤器/挂钩?

我想确保在所有购物过程中都能看到新标题。从产品页面直到通知邮件。

Loi*_*tec 6

以下将允许您自定义购物车、结帐、订单和电子邮件通知中的产品名称,只需一个挂钩功能:

// Just used for testing
function return_custom( $id ) {
    return ' - (' . $id . ')';
}

// Customizing cart item name in cart, checkout, orders and email notifications
add_action( 'woocommerce_before_calculate_totals', 'set_custom_cart_item_name', 10, 1 );
function set_custom_cart_item_name( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Required since Woocommerce version 3.2 for cart items properties changes
    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        // Get the product name and the product ID
        $product_name = $cart_item['data']->get_name();
        $product_id   = $cart_item['data']->get_id();

        // Set the new product name
        $cart_item['data']->set_name( $product_name . return_custom($product_id) );
    }
}
Run Code Online (Sandbox Code Playgroud)

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