Skip to content

Instantly share code, notes, and snippets.

@aolin480
Last active September 27, 2015 19:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aolin480/f9eaa25abd51a8b63dc9 to your computer and use it in GitHub Desktop.
Save aolin480/f9eaa25abd51a8b63dc9 to your computer and use it in GitHub Desktop.
Woocommerce Format product attributes by adding the "or" word for the last element in the array
<?php
// They could be pa_color, pa_flavor, pa_scent, it all depends how you named your product attribute
// all attributes are formated with the prefix pa_ *then your attrbute name*
// get the current product object to get the pa_size attributes, these might differ.
global $product;
// grab an array of product "size" attributes
$_sizes = wc_get_product_terms( $product->id, 'pa_size', array( 'fields' => 'names' ) );
// set a starting increment like a boss!
$i = 0;
// get the full count of the pa_size attributes, again this might be something else depending on your attribute
$size_count = count($_sizes);
// define $total_size variable to be used to house our text statement
$total_size = "";
// for each of the pa_sizes, start doing work son!
foreach( $_sizes as $size ) :
// establish a real count so our brains don't explode
$real_count = $i + 1;
//// ▾ Ternary conditionals are totally rad, but they can also be hard to read, so I tried my best to explain what's going on
// if: $size_count is less or equal to 1, and the real count is 1 then just output the size
// elseif: $size_count is greater than 1 and the real count does not equal the $size_count then add a comma
// elseif: it's the very last size don't output anything, and process the very last value later
// elseif: $size_count is greater than 1 and $real_count equals $size_count finish it off with "or $size"
// else: don't output anything, we reached the end of the world
$total_size .= ( $size_count <= 1 && $real_count == 1 ) ? $size :
( $size_count > 1 && $real_count != $size_count ? $size . ", " :
( $size_count > 1 && $real_count == $size_count ? " or " . $size :
"" )
);
// increment up!
$i++;
endforeach;
/*
* Depending on your attributes it will output something like this. Mine was 14x14, 20x20, 32x32 so it would read
14x14, 20x20, or 32x32
*/
echo "Dimensions: $total_size";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment