Setting a default variation for each product on the child theme functions.php file
I'm trying to set a default variation for each product so I wouldn't need to set it manually on each product separately through the admin panel. I tried to insert the code below but it doesn't work. I'm using Variation Swatcher for WooCommerce plugin as well but from analyzing the DB it shouldn't cause the issue. My code:
function setting_product_default_attributes() {
global $product;
if (!count($default_attributes = get_post_meta($product-get_id(), '_default_attributes'))) {
$new_defaults = array();
$product_attributes = $product-get_attributes();
if (count($product_attributes)) {
foreach ($product_attributes as $key = $attributes) {
$values = explode(',', $product-get_attribute($key));
if (isset($values[0]) !isset($default_attributes[$key])) {
$new_defaults[$key] = sanitize_key($values[0]);
}
}
update_post_meta($product-get_id(), '_default_attributes', $new_defaults);
}
}
}
add_action('woocommerce_before_single_product', 'setting_product_default_attributes');
Topic woocommerce-offtopic Wordpress
Category Web