Reputation: 35
This is the code I use to show available sizes in shoppage/categoriespage. What I am tryin to do is when there are a lot of sizes available example: (XXS, XS, S, M, L, XL, XXL, 3XL, 4XL) then I want to hide this string and show alternative text like (9 sizes availabel) Any help would be appreciated.
add_action( 'woocommerce_shop_loop_item_title', 'mycode_add_size_above_product_title', 20 );
function mycode_add_size_above_product_title() {
global $product;
$size = $product->get_attribute( 'pa_size' );
if ( ! empty( $size ) ) {
echo '<div style="font-size:10px">' . $size . '</div>';
}
I tried this but its showing the sting two times!
if (strlen($string) <=50) {
echo $string;
} else {
echo substr($string, 0, 50) . '...';
}
BEFORE: LEVI'S XXS, XS, S, M, L, XL, XXL, 3XL, 4XL $65.00
EXPECTED RESULT: (only when more then 5 sizes available) LEVI'S 9 Sizes available $65.00
Upvotes: 2
Views: 934
Reputation: 254473
Updated
The following will limit the sizes display to 5 and if more it will display the count of available sizes:
add_action( 'woocommerce_shop_loop_item_title', 'mycode_add_size_above_product_title', 20 );
function mycode_add_size_above_product_title() {
global $product;
if( $sizes = $product->get_attribute( 'pa_size' ) ) {
$count = count( explode(', ', $sizes) ); // The size count
if ( $count > 5 ) {
echo '<div style="font-size:10px">' . $count . ' ' . __("sizes available!") . '</div>';
} else {
echo '<div style="font-size:10px">' . $sizes . '</div>';
}
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
Of course you can adjust the number of sizes to be displayed replacing 5 by any integer…
Upvotes: 1
Reputation: 5190
Put your test for the length inside of the echoing of the div.
if (!empty($size)) {
echo '<div style="font-size:10px">';
if (strlen($size ) <=50) {
echo $size;
} else {
echo substr($size , 0, 50) . '...';
}
echo '</div>';
}
Upvotes: 1