1

I'm trying to get a list of wpsc_product_category terms, for a given category, and have them display in alphabetical order (by name) with links to their pages.

This gives me the right list, but the sort() doesn't work. The terms aren't in alphabetical order. Any help would be greatly appreciated!

<?php 
//display sorted list of wpsc product categories
$category_id = 10;
$terms = get_terms('wpsc_product_category','hide_empty=0&parent='.$category_id);
sort($terms);
if ($terms) {
    foreach($terms as $term) {
        ?>
            <div>
                <div class="caption transparent_class">
                    <a href="<?php get_term_link( $term->slug, 'wpsc_product_category'); ?>" class="wpsc_category_link"><?php echo $term->name; ?></a>
                    <?php if(get_option('wpsc_category_description')) :?>
                    <?php echo '<div class="wpsc_subcategory">'.$term->description.'</div>'; ?>
                    <?php endif;?>
                </div>
            </div>
        <?php
    }
}
?>
1

The default sort order for get_terms is by name. That should give you an alphabetical order. Your sort is what is breaking that order. Your code should work if you just remove that sort.

  • Just realized, the initial code I posted DOES NOT work. It's missing an "echo" before the get_term_link. And without the SORT, the list isn't right (as I believe it's sorting on the id field). I figured out both things and will past the corrected code below in case it helps someone else. – Joe Oct 28 '13 at 23:47
  • I didn't spot the missing echo but adding that echo is not relevant to the sorting problem. – s_ha_dum Oct 28 '13 at 23:54
1

This code works! Sorts by category name (visible name), produces a list of links of categories (that aren't empty) that are children of category_id.

<?php 
//display sorted list of wpsc product categories
$category_id = 10;
$terms = get_terms('wpsc_product_category','hide_empty=1&parent='.$category_id);
usort($terms, function($a, $b)
{
    return strcmp($a->name, $b->name);
});
if ($terms) {
    foreach($terms as $term) {
        ?>
            <div>
                <div class="caption transparent_class">
                    <a href="<?php echo get_term_link( $term->slug, 'wpsc_product_category'); ?>" class="wpsc_category_link"><?php echo $term->name; ?></a>
                    <?php if(get_option('wpsc_category_description')) :?>
                    <?php echo '<div class="wpsc_subcategory">'.$term->description.'</div>'; ?>
                    <?php endif;?>
                </div>
            </div>
        <?php
    }
}
?>
  • As stayed in my answet get_terms has built in sorting the default sort is by name. You should not need to sort the results after the fact. – s_ha_dum Oct 29 '13 at 4:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.