Add Product SKU to Product Title in Woocommerce single product page & shop page

后端 未结 2 1695
感动是毒
感动是毒 2021-01-26 06:25

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

相关标签:
2条回答
  • 2021-01-26 07:16

    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' );
    

    *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

    0 讨论(0)
  • 2021-01-26 07:17

    Just replace this line:

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

    with:

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

    You are done with it!

    0 讨论(0)
提交回复
热议问题