0

I am trying to add product sku before product title. My code is below, when applying this code its adding the sku so much time before my title. But I want to add the title once.

    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 = $_sku . "-" . $_title;

        /*
        *   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 );
}}
add_action( 'draft_to_publish', 'append_sku_to_titles' );

1 Answer 1

1

In the above code. You are adding the SKU code on all the product on every post saved. Instead of all post you should just update only product which you are updating. And send you should check if SKU already added then no need to add it again.

// Call this function each time a product updated
function woo_product_append_sku_to_titles( $product_id ) {
    
    $_product = wc_get_product( $product_id );

    $_sku = $_product->get_sku();
    $_title = $_product->get_title();

    $sku_find = strpos( $_title, $_sku );

    if( $sku_find === false ) {

        $_new_title = $_sku . "-" . $_title;

        global $wpdb;
        
        $where = array( 'ID' => $product_id );
        $wpdb->update( $wpdb->posts, array( 'post_title' => $_new_title ), $where );
    }
}
add_action( 'save_post_product', 'woo_product_append_sku_to_titles', 20, 2 );

Once you update or create any product, the SKU will be added in that post. And if already added then it will not add.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.