1 Востаннє редагувалося Faraon (09.03.2018 16:00:42)

Тема: Створення варіацій продуктів у cms wordpress

Привіт всім. Не можу ніяк написати функціонал додавання варіацій до продукту в wordpress.
В адмінці виводяться поля які ми заповняємо після чого аяксом відправляється запит з цими данними і створюється варіація. Варіація створюється на властивостях, тобто ми заповнили поля, відправили аякс де ми створили нову властивість якщо її ще нема і добавили варіацію по цій властивості. Варіації створюються, але на фронтенді їх чомусь не видно, і навіть коли я їх намагаюся вивести з допомогою

$product->get_available_variations();

то масив пусий, але в адмінці вони відображаються. Я так підозрюю, що коли я їх створюю, то не вірно встановлюю якесь значення через що ми і не можем їх бачити.
Наприклад ось хочу отримати всі варіаціїї продукта по його id

   add_action('init', 'wpc_test');
   function wpc_test()
   {
//       $post = get_posts(array('post_parent'=>9759));
//       var_dump($post);
//       exit();
       
        $product = wc_get_product( 9759 );
        var_dump("POST ID: 9759");
        if(method_exists($product, 'get_available_variations'))
        {
            $variations = $product->get_available_variations();
            var_dump($variations);
            exit();
        }
   }

в результаті отримую пустий масив.
але в адмінці варіації відображаються (на фото видно).

Ось як я їх створюю:

add_action('wp_ajax_create_custom_variations', 'cvp_ajax_create_custom_variations');
add_action('wp_ajax_nopriv_create_custom_variations', 'cvp_ajax_create_custom_variations');
function cvp_ajax_create_custom_variations($import_excel = '', $product_id = 0)
{ 
    if($import_excel != '' && $product_id != 0)
    {
        $_POST['json'] = $import_excel;
        $_POST['post_id'] = $product_id;
    }
    
    $products_data = json_decode($_POST['json'], true);
    //var_dump($_POST['json']);
    if( $_POST['post_id'] == '')
    {
        return false;
    }

    $product_data['available_attributes'] = array("package");
    $product_data['variations'] = array();
    foreach ($products_data as $data) 
    {
        $array = array("attributes"=>array("package" => $data[0]."mg x ".$data[1]." pills"), "price" => $data[3], 'mg'=>$data[0], 'pills'=>$data[1], 'per_pill'=>$data[2]);
        array_push($product_data['variations'], $array);
    }
    
    //$_POST['post_id'] - містить правильний ідентифікатор батьківського продукту
    //$data - також містить правильні дані, так як по них ми створюємо атрибути для продукта, і в результаті все правильнос створюється
    
    wp_set_object_terms((int)$_POST['post_id'], 'variable', 'product_type'); // Set it to a variable product type
    insert_product_attributes((int)$_POST['post_id'], $product_data['available_attributes'], $product_data['variations']); // Add attributes passing the new post id, attributes & variations
    insert_product_variations((int)$_POST['post_id'], $product_data['variations']); // Insert variations passing the new post id & variations   

    //wp_die();
}

function insert_product_attributes ($post_id, $available_attributes, $variations)  
{
    var_dump('$post_id: '.$post_id);
    foreach ($available_attributes as $attribute) // Go through each attribute
    {   
        $values = array(); // Set up an array to store the current attributes values.

        foreach ($variations as $variation) // Loop each variation in the file
        {
            $attribute_keys = array_keys($variation['attributes']); // Get the keys for the current variations attributes

            foreach ($attribute_keys as $key) // Loop through each key
            {
                if ($key === $attribute) // If this attributes key is the top level attribute add the value to the $values array
                {
                    $values[] = $variation['attributes'][$key];
                }
            }
        }

        $values = array_unique($values); // Filter out duplicate values
        wp_set_object_terms($post_id, $values, 'pa_' . $attribute);
    }

    $product_attributes_data = array(); // Setup array to hold our product attributes data

    $product_attributes_data['pa_package'] = array( // Set this attributes array to a key to using the prefix 'pa'

        'name'         => 'pa_package',
        'value'        => '',
        'is_visible'   => '1',
        'is_variation' => '1',
        'is_taxonomy'  => '1'

    );
//    var_dump($product_attributes_data);
    update_post_meta($post_id, '_product_attributes', $product_attributes_data); // Attach the above array to the new posts meta data key '_product_attributes'
}

//var_dump(get_post(10369));
//exit();

function insert_product_variations($post_id, $variations)  
{
    
    delete_variations_product($post_id);
    
    var_dump("POST PARENT: ".$post_id);
    
    foreach ($variations as $index => $variation)
    {
        $variation_post = array( // Setup the post data for the variation

            'post_title'  => 'Variation #'.$index.' of '.count($variations).' for product#'. $post_id,
            'post_name'   => 'product-'.$post_id.'-variation-'.$index,
            'post_status' => 'publish',
            'post_parent' => $post_id,
            'post_type'   => 'product_variation',
            'guid'        => home_url() . '/?product_variation=product-' . $post_id . '-variation-' . $index
        );

        $variation_post_id = wp_insert_post($variation_post); // Insert the variation
//        var_dump($variation['attributes']);
        update_post_meta($variation_post_id, 'cutom_variation_name', str_replace('-', ' ', $variation['attributes']['package']));
        update_post_meta($variation_post_id, 'cvp_mg', $variation['mg']);
        update_post_meta($variation_post_id, 'cvp_pills', $variation['pills']);
        update_post_meta($variation_post_id, 'cvp_price', $variation['price']);
        update_post_meta($variation_post_id, 'cvp_per_pill', $variation['per_pill']);
        update_post_meta($variation_post_id, 'cvp_variation', $variation['per_pill']);
        
        
        foreach ($variation['attributes'] as $attribute => $value) // Loop through the variations attributes
        {   
            $attribute_term = get_term_by('name', $value, 'pa_'.$attribute); // We need to insert the slug not the name into the variation post meta

            var_dump("+++++++++++ ".update_post_meta($variation_post_id, "attribute_pa_".$attribute, $attribute_term->slug));
            var_dump("------------".get_post_meta($variation_post_id, "attribute_pa_".$attribute, true));
        }

        update_post_meta($variation_post_id, '_price', $variation['price']);
        update_post_meta($variation_post_id, '_regular_price', $variation['price']);
    }
}

function delete_variations_product($post_id)
{
    $product = wc_get_product( $post_id );
    var_dump("POST ID: ".$post_id);
    if(method_exists($product, 'get_available_variations'))
    {
        
    var_dump("POST ID 2: ".$post_id);
        $args = array(
            'numberposts' => -1,
            'post_parent' => $post_id
        );
        
        $get_posts = get_posts( $args );
        $variations = $product->get_available_variations();
        f_dump($args);
        f_dump($get_posts);
        foreach ($get_posts as $key => $variation) 
        {
            
            var_dump("DELETE POST 1");
            if(!get_post_meta($variation->ID, 'cvp_variation', true) && get_post_meta($variation->ID, 'cvp_variation', true) != '')
            {
                continue;
            }
            var_dump("DELETE POST 2");
            wp_delete_post( $variation->ID );
        } 
    }
}

функція delete_variations_product() на данний момент нічого не робить так як вона намагається отримати по id варіації продукта після чого їх видалити, але так як нам цілий час повертає пустий масив то ми нічого не видаляємо і варіації просто добавляються до все існуючих.
Ніяк не можу зрозуміти в чому проблема, прошу вашої допомоги. Якщо погано пояснив, то так і скажіть, спробую по іншому. Дуже потрібно вирішити цю проблему сьогодні.

Post's attachments

screenshot-zoo.stepasyuk.org.ua-2018.03.09-15-47-58.png 261.72 kb, 190 downloads since 2018-03-09 

2 Востаннє редагувалося Faraon (10.03.2018 00:10:12)

Re: Створення варіацій продуктів у cms wordpress

У wordpress є така штука як дефолтна варіація яка відображається зразу при переході на сторінку. Коли я настворював  потрібні мені варіації, я забув встановити яка з них буде дефолтною через що і виникала ця проблема.
ось приклад функції яку я викликаю в самому кінці

function insert_variations_default_attributes( $post_id, $variations ){
    if(empty(get_post_meta($post_id, '_default_attributes', true )))
    {
        $variations_default_attributes['pa_package'] = get_term_by( 'name', $variations[0]['attributes']['package'], 'pa_package' )->slug;
        update_post_meta( $post_id, '_default_attributes', $variations_default_attributes );
    }
}