将产品SKU添加到Woocommerce单一产品页面&中的产品标题中;店铺页面 [英] Add Product SKU to Product Title in Woocommerce single product page & shop page

查看:85
本文介绍了将产品SKU添加到Woocommerce单一产品页面&中的产品标题中;店铺页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将产品sku添加到实际产品标题中. 例如,如果产品名称为连衣裙设计"&产品sku为"2790" 新产品的标题应为连衣裙设计-2790".

i want to add product sku to actual product title. for example, if product name is "Dress design" & product sku is "2790" the new product title should be "Dress design - 2790".

我尝试了以下代码.但是此代码用单个产品页面上的产品SKU替换了产品标题.

i had tried following code. but this code replaces the product title by the product SKU on single product pages.

add_action( 'woocommerce_single_product_summary', 'replace_product_title_by_product_sku', 4 );
function replace_product_title_by_product_sku() {
    global $product;

    if ( $product->get_sku() ) {
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_title', 5 );
        add_action( 'woocommerce_single_product_summary', 'display_product_sku_as_title', 5 );
    }
}

function display_product_sku_as_title() {
    global $product;

    echo '<h1 class="product_title entry-title">' . esc_html( $product->get_sku() ) . '</h1>';
}

但是我想要产品标题+ Sku",&我想在单个产品页面上显示它商店页面和结帐页面购物车页面.

but i want "product title + Sku", & i want to display it on single product page & shop page & checkout page & cart page.

推荐答案

为什么不通过将SKU附加到当前标题而不是仅更改视图来直接更改标题?

Why don't you directly change the titles by appending SKU to current titles instead of changing the view only?

function append_sku_to_titles() {

 $all_ids = get_posts( array(
    'post_type' => 'product',
    'numberposts' => -1,
    'post_status' => 'publish',
    'fields' => 'ids'
));

foreach ( $all_ids as $id ) {
        $_product = wc_get_product( $id );
        $_sku = $_product->get_sku();
        $_title = $_product->get_title();

        $new_title = $_title . " " . $_sku;

        /*
        *   Tested.
        *   echo $_title + $_sku;
        *   echo("<script>console.log('Old: ".$_title. " - ". $_sku."');</script>");
        *   echo("<script>console.log('New: ".$new_title."');</script>");
        */

        $updated = array();
        $updated['ID'] = $id;
        $updated['post_title'] = $new_title;

        wp_update_post( $updated );
}}

//Call the function with footer (*Attention)
add_action( 'wp_footer', 'append_sku_to_titles' );

*注意:更改标题后,请不要忘记删除此行(add_action),因为它会在每次加载页面时尝试更改它们.

*Attention: Do not forget to remove this line (add_action) after you change the titles since it will try to change them whenever a page loads

这篇关于将产品SKU添加到Woocommerce单一产品页面&amp;中的产品标题中;店铺页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆