I am trying to show specific attribute value in custom page and how i can show it Alphabatically
<?php
$query = new WP_Query($args);
$products_by_attribute = array(); // To hold products grouped by attribute
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
global $product;
// Get product attributes
$attributes = $product->get_attributes();
// Change 'color' to your desired attribute slug
if (isset($attributes['color'])) {
$attribute_value = $attributes['color']['value'];
// Group products by their attribute value
if (!isset($products_by_attribute[$attribute_value])) {
$products_by_attribute[$attribute_value] = array();
}
$products_by_attribute[$attribute_value][] = $product;
}
}
wp_reset_postdata(); // Reset post data
// Sort the attribute values alphabetically
ksort($products_by_attribute);
echo '</div>'; // .product-items
}
}
?>
Attributes Color = Aa,Bb,yellow2,red,green,green1,green2,red1,yellow
Try using this code, should work
I executed the query to get products, then grouped products by their 'color' attribute, then sorted these groups alphabetically using ksort()
I then displayed each group with its products listed.
replace 'color' with the actual attribute slug you want to use. The esc_html
and esc_url
functions ensure that the output is well escaped for security.
<?php
$query = new WP_Query($args);
$products_by_attribute = array();
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
global $product;
$attributes = $product->get_attributes();
if (isset($attributes['color'])) {
$attribute_value = $attributes['color']['value'];
if (!isset($products_by_attribute[$attribute_value])) {
$products_by_attribute[$attribute_value] = array();
}
$products_by_attribute[$attribute_value][] = $product;
}
}
wp_reset_postdata();
ksort($products_by_attribute);
foreach ($products_by_attribute as $attribute_value => $products) {
echo '<h2>' . esc_html($attribute_value) . '</h2>';
echo '<ul>';
foreach ($products as $product) {
echo '<li><a href="' . esc_url(get_permalink($product->get_id())) . '">' . esc_html(get_the_title($product->get_id())) . '</a></li>';
}
echo '</ul>';
}
}
?>