Search code examples
phpwordpresswoocommercehook-woocommerce

how to convert woocommerce product category to woocommerce product attribute - no plugin i wanna do this programicality


I have a WordPress site and I use the WooCommerce plugin, I created a product category called Brand and placed the brands in my store under this category. But now I realized that it is better to convert these brands into product features because I need to be able to add a brand-based filter to the product category page. In this way, I got help from ChatGPT and found answers.

I designed a plugin for this problem, this plugin adds a page in the management panel and displays a list of products, when I click on the start button, it sends the product ID and the product brand name as an ajax. Ajax sending code:

<script>
    jQuery(document).ready(function($) {
        $('#AddAttrToBrand').click(function(e) {
            e.preventDefault();
            var Products = $('tr[id^=Product_]');
            for (let index = 0; index < Products.length; index++) {
                var Element = Products[index].id;
                var ElementArr = Element.split('_');
                var ProductID = ElementArr[1];
                var AttrTitle = ElementArr[2];
                $.ajax({
                    type: "POST",
                    url: "<?php echo admin_url('admin-ajax.php'); ?>",
                    data: {
                        ProductID: ProductID,
                        AttrTitle: AttrTitle,
                        action: 'BrandsCorrection'
                    },
                    success: function(response) {

                    }
                });
            }
        });
    });
</script>

And I created a function for this ajax that receives the id and brand name and does things according to it. Ajax receiver function:

add_action('wp_ajax_BrandsCorrection', 'BrandsCorrectionCallBack');
function BrandsCorrectionCallBack()
{
    $product_id = intval($_POST['ProductID']);
    $attribute_value = $_POST['AttrTitle'];
    $attribute_name = 'pa_brand';
    // Get the product object
    $product = wc_get_product($product_id);

    // Check if the product exists
    if ($product) {
        wp_set_post_terms($product_id, $attribute_value, $attribute_name, false);
        // Save the product to update the attribute
        $product->save();
    }
    // die();
}

This code adds the property to the product and when I call the function:

<?php echo wc_get_product_terms(get_the_ID(), 'pa_brand', array('fields' => 'names'))[0]; ?>

it displays the brand correctly, but this brand is not displayed on the single page of the product features section, and this feature is not added on the product editing page either. Can anyone guide me?


Solution

  • I found the solution to my problem and I share the solution for those who have the same problem:

    add_action('wp_ajax_BrandsCorrection', 'BrandsCorrectionCallBack');
    function BrandsCorrectionCallBack()
    {
        $product_id = intval($_POST['ProductID']);
        $attribute_value = $_POST['AttrTitle'];
        $attribute_name = 'pa_brand';
        $position = 0;
        $existing_data_attributes = (array) get_post_meta($product_id, '_product_attributes', true);
        if (sizeof($existing_data_attributes) > 0)
            $position = sizeof($existing_data_attributes);
        // Get the product object
        $product = wc_get_product($product_id);
        // Check if the product exists
        if (!in_array($attribute_name, array_keys($existing_data_attributes))) {
            $position++;
        }
        // Setting formatted post meta data if it doesn't exist in the array
        $existing_data_attributes[$attribute_name] = array(
            'name'         => $attribute_name,
            'value'        => '',
            'position'     => $position,
            'is_visible'   => 1,
            'is_variation' => 1,
            'is_taxonomy'  => 1
        );
        wp_set_post_terms($product_id, $attribute_value, $attribute_name, false);
        // Save the product to update the attribute
        $product->save();
        update_post_meta($product_id, '_product_attributes', $existing_data_attributes);
        print_r($existing_data_attributes);
    }