October 27, 2024
Chicago 12, Melborne City, USA
PHP

Getting the chosen Product Category on my custom form to the newly created product


I’ve been trying to fix this issue for two days now. The user selects their desired category on my form, and the form submission is supposed to handle it and pass it to the newly created product, but the selected category isn’t being applied.

This is part of my form, so the user can choose and select the category:

<h2>Item Information</h2>
<label>Product Category:</label>
<div>
    <?php
    $categories = get_terms(['taxonomy' => 'product_cat', 'hide_empty' => false]);
    foreach ($categories as $category) {
        echo "<label><input type="checkbox" name="product_category[]" value="{$category->term_id}"> {$category->name}</label><br/>";
    }
    ?>
</div>

This is my form submission code:

// Form submission code
if (isset($_POST['submit_shoe_product'])) {
    // Validate required fields except for product_image, as it may be pre-populated
    if (empty($_POST['consigner']) || empty($_POST['branch']) || 
        empty($_POST['style_code']) || empty($_POST['product_title']) ||
        empty($_POST['size']) || empty($_POST['condition']) || empty($_POST['quantity']) || 
        empty($_POST['cost_price']) || empty($_POST['selling_price'])) {
        echo '<div class="notice notice-error jg-notice"><p>All fields are required. Please fill in all the fields.</p></div>';
        return;
    }

    // Check if the product with the given title already exists
    $product_id = tayp_get_existing_product_id_by_title($_POST['product_title']);

    // Retrieve selected product category names directly
    $selected_category_names = isset($_POST['product_category']) ? $_POST['product_category'] : [];

    // Debugging message
    echo '<div class="notice notice-info"><p>Selected Categories: ' . implode(', ', $selected_category_names) . '</p></div>';

    // Check if replace_image is checked and a new image is uploaded
    $attachment_id = null;
    if (!empty($_FILES['product_image']['name']) && isset($_POST['replace_image'])) {
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        $uploaded_file = $_FILES['product_image'];
        $upload = wp_handle_upload($uploaded_file, ['test_form' => false]);
        if ($upload && !isset($upload['error'])) {
            $attachment = [
                'post_mime_type' => $upload['type'],
                'post_title' => sanitize_file_name($uploaded_file['name']),
                'post_content' => '',
                'post_status' => 'inherit'
            ];
            $attachment_id = wp_insert_attachment($attachment, $upload['file']);
            require_once(ABSPATH . 'wp-admin/includes/image.php');
            $attachment_data = wp_generate_attachment_metadata($attachment_id, $upload['file']);
            wp_update_attachment_metadata($attachment_id, $attachment_data);
        }
    }

    if ($product_id) {
        if ($attachment_id) {
            set_post_thumbnail($product_id, $attachment_id); // Set new image as featured image if uploaded
        }
        // Add new variation if product exists
        $variation_id = tayp_create_product_variation($product_id, $_POST);

        // Apply categories to the main product using category names
        if (taxonomy_exists('product_cat')) {
            $category_result = wp_set_object_terms($product_id, $selected_category_names, 'product_cat', true);
            if (is_wp_error($category_result)) {
                echo '<div class="notice notice-error"><p>Failed to set categories: ' . $category_result->get_error_message() . '</p></div>';
            }
        } else {
            echo '<div class="notice notice-error"><p>Product category taxonomy does not exist.</p></div>';
        }
    } else {
        // Create a new variable product if none exists
        $product = new WC_Product_Variable();
        $product->set_name($_POST['product_title']);
        $product->save();

        if ($attachment_id) {
            set_post_thumbnail($product->get_id(), $attachment_id);
        }

        // Set product attributes, categories, etc.
        $variation_id = tayp_create_product_variation($product->get_id(), $_POST);

        // Apply categories to the new product using category names
        if (taxonomy_exists('product_cat')) {
            $category_result = wp_set_object_terms($product->get_id(), $selected_category_names, 'product_cat', true);
            if (is_wp_error($category_result)) {
                echo '<div class="notice notice-error"><p>Failed to set categories: ' . $category_result->get_error_message() . '</p></div>';
            }
        } else {
            echo '<div class="notice notice-error"><p>Product category taxonomy does not exist.</p></div>';
        }
    }

    // Notify user
    echo $variation_id 
        ? '<div class="notice notice-success"><p>Product variation created successfully!</p></div>'
        : '<div class="notice notice-error"><p>Failed to create product variation.</p></div>';
}

// Function to create a product variation
function tayp_create_product_variation($product_id, $data) {
    $variation = new WC_Product_Variation();
    $variation->set_parent_id($product_id);

    // Use slugs for attributes, as WooCommerce expects term slugs, not term IDs
    $variation->set_attributes([
        'pa_size' => $data['size'],          // Using slug from the form data
        'pa_condition' => $data['condition'], // Using slug from the form data
    ]);

    // Set custom style code
    $variation->update_meta_data('_style_code', $data['style_code']);
    
    // Set other variation details
    $variation->update_meta_data('_custom_quantity_stock', $data['quantity']);
    $variation->update_meta_data('_custom_cost_price', $data['cost_price']);
    $variation->set_regular_price($data['selling_price']);
    
    // Add Branch and Consigner as meta data for the variation (matching custom field names)
    $variation->update_meta_data('_variation_branch', intval($data['branch']));
    $variation->update_meta_data('_variation_consigner', intval($data['consigner']));

    $variation->save();

    return $variation->get_id();
}`

I tried multiple scenario object etc… but the same, I need help and fresh eyes to check it.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video