0

每当保存新产品时,我都需要创建一个由 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>
4

1 回答 1

0

简单的解决方案是在函数内部使用 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 );
            }
        }


}
于 2020-03-05T16:07:47.570 回答