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