为woocommerce产品创建单一变体

时间:2017-07-09 17:57:03

标签: php arrays woocommerce parent-child

我需要为任何woocommerce产品创建一个单独的变体,但每次我点击保存它会创建另一个变体。 我在functions.php

的循环之外工作

为什么每次我点击保存它会创建另一个变体,需要帮助才能创建1个变体/子帖

add_action (save_post, create_new_vars);
function create_new_vars ($post) {
global $post;
$children = get_pages('child_of='.$post->ID);
if( count( $children ) >= 1 ) {     
return;
}

$my_post = array(
    'post_title' => 'Color  for #' . $post->ID,
    'post_name' => get_the_title($post->ID),
    'post_status' => 'publish',
    'post_parent' => $post->ID,
    'post_type' => 'product_variation',
    'guid' => home_url() . '/?product_variation=' . get_the_title($post->ID)
);

    remove_action('save_post', __FUNCTION__);
    $attID = wp_insert_post($my_post);

}

1 个答案:

答案 0 :(得分:0)

好的答案是

add_action (save_post, create_new_vars);
function create_new_vars ($post) {
global $post;
$args  = array(
    'post_title' => 'Color  for #' . $post->ID,
    'post_name' => get_the_title($post->ID),
    'post_status' => 'publish',
    'post_parent' => $post->ID,
    'post_type' => 'product_variation',
    'guid' => home_url() . '/?product_variation=' . get_the_title($post->ID)    
);
$children = get_children( $args );
if( count( $children ) < 1 ) {      


$my_post = array(
    'post_title' => 'Color  for #' . $post->ID,
    'post_name' => get_the_title($post->ID),
    'post_status' => 'publish',
    'post_parent' => $post->ID,
    'post_type' => 'product_variation',
    'guid' => home_url() . '/?product_variation=' . get_the_title($post->ID)
);

    remove_action('save_post', __FUNCTION__);
    $attID = wp_insert_post($my_post);

}
}