Add SKU in Product Title

时间:2021-07-16 作者:Shah Nawaze Pavel

我正在尝试在产品标题之前添加产品sku。下面是我的代码,当应用此代码时,它会在我的标题之前添加sku。但我想添加一次标题。

    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 个回复
SO网友:Dipendra Pancholi

在上述代码中。您正在为保存的每个帖子上的所有产品添加SKU代码。你应该只更新你正在更新的产品,而不是所有的帖子。并发送您应该检查SKU是否已添加,然后无需再次添加。

// 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 );
更新或创建任何产品后,SKU将添加到该帖子中。如果已经添加,则不会添加。

相关推荐