【问题标题】:Automatically create Woocommerce SKU with save_post hook使用 save_post 钩子自动创建 Woocommerce SKU
【发布时间】:2020-03-05 12:54:30
【问题描述】:

我需要在每次保存新产品时创建一个由 3 个自定义分类法组成的唯一 SKU,但无法获取自定义分类法。这是我目前所拥有的:

add_action( 'save_post', 'set_sku', 10,3 );

function set_sku( $post_id, $post, $update ) {
    // Only want to set if this is a new post!
    if ( $update ){
        return;
    }

    // Only set for post_type = post!
    if ( 'product' !== $post->post_type ) {
        return;
    }
    $producer = strip_tags( get_the_term_list( $post_id, 'producer') );
    $vintage = strip_tags( get_the_term_list( $post_id, 'vintage') );
    $bottle_size = strip_tags( get_the_term_list( $post_id, 'bottle_size') );
    $your_sku = $producer . "|" . $vintage . "|" . $bottle_size;

    if( empty( get_post_meta( $post_id, '_sku', true ) ) ) {
        update_post_meta( $post_id, '_sku', $your_sku );
    }


}

创建新产品时生成的 SKU 如下:

||

PS 只有一个值分配给每个自定义分类。

任何帮助表示赞赏。我在前端使用了一个类似的函数来正确显示数据,这里有一个示例:

<?php 

    $products = new WP_Query( array(
    'post_type'         => 'product',
    'posts_per_page'    => -1,

    ) );


    if ( $products->have_posts() ) :

        while ( $products->have_posts() ) : $products->the_post(); $id = $product->get_id();?>

        <tr>
            <td><?php echo $producer = strip_tags( get_the_term_list( $id, 'producer') ); ?</td>

【问题讨论】:

    标签: woocommerce save hook custom-taxonomy sku


    【解决方案1】:

    简单的解决方案是在函数内部使用 wc_get_products 循环遍历产品。似乎是在浪费资源,并希望只使用当前的帖子 ID,但它确实有效,而且 WP 毕竟是建立在循环上的。经过测试和工作,是自动化和控制 SKU 创建的一种很酷的方法。

    add_action( 'save_post', 'set_sku', 10,3 );
    
    function set_sku( $post_id, $post, $update ) {
        // Only want to set if this is a new post!
        if ( $update ){
            return;
        }
    
        // Only set for post_type = post!
        if ( 'product' !== $post->post_type ) {
            return;
        }
    
    
    
        $args = array(
                'limit' => 9999999,
                'orderby'  => 'name',
            );
    
            $productData = wc_get_products( $args );
    
            foreach ( $productData as $product ){
    
                $productId = $product->get_id();
                $producer = strip_tags( get_the_term_list( $productId, 'producer') );
                $vintage = strip_tags( get_the_term_list( $productId, 'vintage') );
                $bottle_size = strip_tags( get_the_term_list( $productId, 'bottle_size') );
                $your_sku = $producer . "|" . $vintage . "|" . $bottle_size;
    
                if( empty( get_post_meta( $post_id, '_sku', true ) ) ) {
                    update_post_meta( $post_id, '_sku', $your_sku );
                }
            }
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      • 2020-08-04
      相关资源
      最近更新 更多