PluginUs.Net - Business Tools for WooCommerce and WordPress

[realize your idea - make your dreams come true]

Support Forum

You need to log-in to create request (topic) to the support

2 attributes questions

The support doesn work on Saturdays and Sundays, so some Friday requests can be answered on Monday. If you have problems with registration ask help on contact us page please
If you not got email within 24~36 business hours, firstly check your spam box, and if no any email from the support there - back to the forum and read answer here. DO NOT ANSWER ON EMAILS [noreply@pluginus.net] FROM THE FORUM!! Emails are just for your info, all answers should be published only here.
The support doesn work on Saturdays and Sundays, so some Friday requests can be answered on Monday.

Hello I am using the paid Pro version of BEAr and I have 2 questions.

In some of my products I have a local attribute called cost-price and it is what the product costs me to buy it. I want to make it global, Is there a way to do this with your plugin?

Also is there a way I can modify an attribute value based on other on the fly? I mean if I create a new global attribute that is empty, can I use BEAR to give value to it based on other attributes?
I want for example to mass change a value to something like ( (Selling_Price - Cost_Price) / Cost_Price ) * 10
Is this doable at Meta Fields?

Thanks
Giorgos

Hello Giogos

Thank you for your questions. Unfortunately, BEAR plugin cannot do these operations directly through the interface, but both tasks are achievable using custom PHP scripts and database queries.

Here's what I propose:

Solution for Question 1: Converting Local Attribute to Global

Steps:

  1. First, manually create a global attribute called cost-price in WooCommerce > Products > Attributes
  2. Add the first PHP script I'll provide to your theme's functions.php file
  3. Activate the conversion by visiting: yourdomain.com/?convert_cost_price_attr=SECRET_KEY_12345
  4. The script will automatically find all products with the local cost-price attribute, convert them to the global attribute, and clean up the local versions

Solution for Question 2: Calculating Formula and Storing in Meta Field

Steps:

  1. Add the second PHP script to your theme's functions.php file
  2. Activate the calculation by visiting: yourdomain.com/?calculate_margin_meta=SECRET_KEY_67890
  3. The script will calculate the formula ((Selling_Price - Cost_Price) / Cost_Price) * 10 for all products
  4. Results will be stored in a meta field called _margin_calculated
  5. After that, you can bulk edit this meta field using BEAR's Meta Fields functionality

Important notes:

  • Replace SECRET_KEY_12345 and SECRET_KEY_67890 with your own secret keys for security
  • Make a full database backup before running these scripts
  • The scripts will show progress on screen as they process your products
  • After running successfully, you can remove the scripts from functions.php

I'll send you both PHP scripts in the next message. Let me know if you need any clarification!

FIRST:

// Add to theme functions.php
// Activation: yourdomain.com/?convert_cost_price_attr=SECRET_KEY_12345

add_action('init', 'convert_local_to_global_cost_price');

function convert_local_to_global_cost_price() {

// Check secret key
    if (!isset($_GET['convert_cost_price_attr']) || $_GET['convert_cost_price_attr'] !== 'SECRET_KEY_12345') {
        return;
    }

// Increase limits
    set_time_limit(0);
    ini_set('memory_limit', '512M');

    echo '<h2>Converting local attribute"cost-price" to global"pa_cost-price"</h2>';

// 1. Check if the global attribute pa_cost-price exists 
    $attribute_taxonomy = 'pa_cost-price';
    if (!taxonomy_exists($attribute_taxonomy)) {
        echo '<p style="color:red;">ERROR: Global attribute"pa_cost-price" does not exist! Create it first in WooCommerce > Products > Attributes</p>';
        die();
    }

// 2. Get all products 
    $args = array(
        'post_type' => 'product',
        'posts_per_page' => -1,
        'post_status' => 'any'
    );

    $products = get_posts($args);
    $converted = 0;

    foreach ($products as $product_post) {
        $product_id = $product_post->ID;
        $product = wc_get_product($product_id);

        if (!$product)
            continue;

// Get current attributes 
        $attributes = $product->get_attributes();

// Find local cost-price 
        $local_cost_price_value = null;
        $local_attr_key = null;

        foreach ($attributes as $key => $attribute) {
            if ($attribute->is_taxonomy() === false && strtolower($attribute->get_name()) === 'cost-price') {
                $local_cost_price_value = $attribute->get_options();
                $local_attr_key = $key;
                break;
            }
        }

        if ($local_cost_price_value) {
// Value found
            $value = is_array($local_cost_price_value) ? $local_cost_price_value[0] : $local_cost_price_value;

// Create/get term for the global attribute
            $term = term_exists($value, $attribute_taxonomy);
            if (!$term) {
                $term = wp_insert_term($value, $attribute_taxonomy);
            }
            $term_id = is_array($term) ? $term['term_id'] : $term;

// Assign the global attribute to the product
            wp_set_object_terms($product_id, (int) $term_id, $attribute_taxonomy);

// Add a global attribute to the product attributes array
            $global_attribute = new WC_Product_Attribute();
            $global_attribute->set_id(wc_attribute_taxonomy_id_by_name($attribute_taxonomy));
            $global_attribute->set_name($attribute_taxonomy);
            $global_attribute->set_options(array($term_id));
            $global_attribute->set_visible(true);
            $global_attribute->set_variation(false);

// Remove a local attribute
            unset($attributes[$local_attr_key]);

// Add a global attribute
            $attributes[$attribute_taxonomy] = $global_attribute;

            $product->set_attributes($attributes);
            $product->save();

            $converted++;
            echo"<p>✓ Product ID {$product_id}: converted value '{$value}'</p>";
        }
    }

    echo"<h3>Conversion complete! Total products converted: {$converted}</h3>";
    die();
}

 

SECOND:

// Add to functions.php
// Activation: yourdomain.com/?calculate_margin_meta=SECRET_KEY_67890

add_action('init', 'calculate_margin_to_meta_field');

function calculate_margin_to_meta_field() {

    if (!isset($_GET['calculate_margin_meta']) || $_GET['calculate_margin_meta'] !== 'SECRET_KEY_67890') {
        return;
    }

    set_time_limit(0);
    ini_set('memory_limit', '512M');

    echo '<h2>Calculating the margin formula for the meta field</h2>';

    echo '<p>Formula: ((Sale Price - Cost Price) / Cost Price) * 10</p>';

    $args = array(
        'post_type' => 'product',
        'posts_per_page' => -1,
        'post_status' => 'any'
    );

    $products = get_posts($args);

    $processed = 0;

    $skipped = 0;

    foreach ($products as $product_post) {

        $product_id = $product_post->ID;

        $product = wc_get_product($product_id);

        if (!$product)
            continue;

// Get the sale price (regular price)

        $selling_price = floatval($product->get_regular_price());

// Get the cost price from the custom pa_cost-price attribute

        $cost_price_terms = wp_get_post_terms($product_id, 'pa_cost-price', array('fields' => 'names'));

        $cost_price = !empty($cost_price_terms) ? floatval($cost_price_terms[0]) : 0;

// If cost_price = 0, skip

        if ($cost_price == 0 || $selling_price == 0) {

            $skipped++;

            echo"<p style='color:orange;'>⊘ Product ID {$product_id}: skipped (cost_price={$cost_price}, selling_price={$selling_price})</p>";

            continue;
        }

// Calculation using formula

        $margin = (($selling_price - $cost_price) / $cost_price) * 10;

        $margin = round($margin, 2);

// Write to meta field
        update_post_meta($product_id, '_margin_calculated', $margin);

        $processed++;
        echo"<p>✓ Product ID {$product_id}: margin = {$margin} (price={$selling_price}, cost={$cost_price})</p>";
    }

    echo"<h3>Calculation complete! Processed: {$processed}, Skipped: {$skipped}</h3>";

    die();
}

 

ATTENTION: before making any operations with your site database make its backup by any tool, no warranty for expected result

For further support place please actual purchase code of the plugin into the private area of this ticket:
https://share.pluginus.net/image/i20230222134241.png
https://share.pluginus.net/image/i20230222134615.png
https://share.pluginus.net/image/i20230222134511.png

 

Thank you Alex, will try those!

Hello Giorgos

Welcome :)