【问题标题】:How to programmaticaly change product name everywhere in woocommerce?如何以编程方式在 woocommerce 中随处更改产品名称?
【发布时间】:2020-07-02 23:07:54
【问题描述】:

我正在尝试美化我的产品名称,我需要在任何地方应用更改(目录、购物车、结帐、小部件...)等

其实,我做到了:

目录(循环)单品:

add_filter('the_title', 'new_title', 10, 2);
function new_title($title, $id) {
    if('product' == get_post_type($id)){
        $title = rename_woo_product($title, $id); // My function to rename
    }
    return $title;
}

在产品标题标签和 yoast 中:

add_filter( 'pre_get_document_title', 'generate_custom_title', 10 );
add_filter('wpseo_title', 'generate_custom_title', 15);
function generate_custom_title($title) {
    if(  is_singular( 'product') ) {
        $title = get_the_title();
    }
    return $title;
}

购物车和结帐:

add_filter( 'woocommerce_cart_item_name', 'custom_variation_item_name', 10, 3 );
function custom_variation_item_name( $item_name,  $cart_item,  $cart_item_key ){
    $product_item = $cart_item['data'];

    $item_name = get_the_title( $cart_item['product_id'] );

    if(!empty($product_item) && $product_item->is_type( 'variation' ) ) {
        $item_name = $item_name . '<br>' . $cart_item['data']->attribute_summary;
    }

    if(is_cart()){
        $item_name = sprintf( '<a href="%s">%s</a>', esc_url( $cart_item['data']->get_permalink() ), $item_name );
    }

    return $item_name;
}

我不知道这是否是最好的方法,但它适用于此。但是例如我使用了woocommerce的Recent Viewed Products小部件,并且产品标题没有更新.. Yith 愿望清单也是如此

有没有更好的方法来更新产品名称并将其应用到任何地方?

【问题讨论】:

    标签: php wordpress woocommerce


    【解决方案1】:

    您也可以使用复合钩子woocommerce_product_get_name,例如:

    add_filter('woocommerce_product_get_name', 'filter_wc_product_get_name', 10, 2); // For "product" post type
    add_filter('woocommerce_product_variation_get_name', 'filter_wc_product_get_name', 10, 2); // For "product_variation" post type
    function filter_wc_product_get_name( $name, $product ){
        if ( ! is_admin() ) {
            $name = rename_woo_product($name, $product->get_id());
        }
        return $name;  
    }
    

    它应该替换挂在woocommerce_cart_item_name 过滤器挂钩中的自定义函数。

    【讨论】:

    • 是的!谢谢@LoicTheAztec!然而,这个钩子并没有取代任何东西,它提供了一个补充。它适用于愿望清单和小部件!不强制产品单标题
    • @Efbi 您没有在您的问题中询问有关第三方未知插件“愿望清单”的问题(尝试将挂钩优先级从 10 增加到 99999)而且我没有说挂钩会取代一切...
    • 我的意思是,我正在寻找一种在任何地方修改产品名称的方法。例如,我提到了 woocommerce 小部件和 Yith Wishlist。我认为任何插件都从某些东西中获取产品名称,我需要为将来的第三方修改它
    • @Efbi 在 StackOverFlow 中,规则是当时的一个问题……我在这里的回答只是为您提供WC_Product get_name() 方法的相关过滤器钩子,它可能用于购物车,结帐相关模板.对于 YITH 插件,你需要进入他们的代码,看看他们是如何处理产品标题的……
    猜你喜欢
    • 2021-05-09
    • 1970-01-01
    • 1970-01-01
    • 2018-04-27
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-30
    相关资源
    最近更新 更多