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