First, you need to ensure that your count($args['options']
is actually 1.
Check the following example:
You can see that when I print_r($args['options'])
, I got 4 elements, so count($args['options']
here is 4. But if you look at the dropdown beneath it, you see that it only has 1 option.
Why? Because variations (and their attributes) that do not have prices will not be shown in your store!
So how can you select the first option in this case (or in any cases), based on the number of options in the generated HTML? You can use jQuery with the following code:
jQuery(document).ready(function($) {
// Loop through each select element within the table with class .variations
$('.variations select').each(function() {
var $select = $(this); // Cache the current select element
var numberOfOptions = $select.find('option').length; // Get the number of options, including the first, placeholder option
// Check if the select contains exactly 2 options
if (numberOfOptions === 2) {
// Select the last option
$select.val($select.find('option:last').val()).change(); // Change the value and trigger change event
}
});
});
Note: In this case, the variation table has class .variations
. Check your code and change the class if needed.