Created
June 8, 2024 17:13
-
-
Save cyberdev/37b1b723d0c1da61f1eb700b19f417ad to your computer and use it in GitHub Desktop.
Set default product attribute when only one option
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function get_variation_slug($taxonomy, $term_name) | |
{ | |
if (term_exists($term_name, $taxonomy)) { | |
$term_slug = get_term_by('name', $term_name, $taxonomy)->slug; | |
} else { | |
$term_slug = ''; | |
} | |
return $term_slug; | |
} | |
global $product; | |
if (!count($default_attributes = get_post_meta($product->get_id(), '_default_attributes'))) { | |
$new_defaults = []; | |
$product_attributes = $product->get_attributes(); | |
if (count($product_attributes)) { | |
foreach ($product_attributes as $key => $attributes) { | |
$values = explode(',', $product->get_attribute($key)); | |
if (count($values) == 1 && !isset($default_attributes[$key])) { | |
$key_val = get_variation_slug($key, $values[0]); | |
$new_defaults[$key] = $key_val; | |
} | |
} | |
if(count($new_defaults)) { | |
update_post_meta($product->get_id(), '_default_attributes', $new_defaults); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment