0

I have the following script and i need to sort the inner foreach loop alphabetically but with no success.

$args = array( 
        'post_type' => 'clinical_sites',
        'tax_query' => array( 
                    'relation' => 'AND',
                    array(
                            'taxonomy' => 'research', 
                            'field' => 'slug',
                            'operator' => 'AND',
                            'hide_empty' => false,
                            'terms' => $researchName
                    ),
                    array( 
                            'taxonomy' => 'country',
                            'hide_empty' => false,
                            'operator' => 'IN',
                            'field'    => 'term_id',
                            'terms' => $fatherTermId 
                        ),
                    ),
        'hide_empty' => true,
        'posts_per_page'=>-1,
        'parent' => '1'
    );
    $query = new WP_Query( $args );
    if ( $query->have_posts() ) {
        while( $query->have_posts() ) { $query->the_post();

            $args3 = array( 
                'orderby'  => 'ID',
                'order'    => 'DESC',
                'childless' => true
            );
            $terms = wp_get_object_terms( $post->ID, 'country', $args3  );
            if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
                foreach ( $terms as $parent_term ) {


                        ?><option value="<?=$parent_term->name; ?>" data-is-parent="<?=$isparent?>" data-term_id="<?=$parent_term->term_id; ?>" ><?php echo $parent_term->name?></option><?php
                } 
            }
        }
    }

Help will be appreciated.

  • Just change 'orderby' => 'ID' to 'orderby' => 'name' and your terms will be ordered alphabetically. – swissspidy Jan 21 '18 at 16:22
  • @swissspidy can you post that as an answer? Comments are for clarifying questions, and I can't give you rep for a comment – Tom J Nowell Jan 21 '18 at 16:32
  • @TomJNowell Done :-) – swissspidy Jan 21 '18 at 16:38
1

It looks like all you need to do is change toe orderby argument of your wp_get_object_terms() call. After all, that's what you're looping through further down.

If you change 'orderby' => 'ID' to 'orderby' => 'name', your terms will be ordered alphabetically.

  • Not working :( I think its because of the outer while loop that loops through the posts, and i need to display the terms one by one in a dropdown menu. – shafshaf Jan 22 '18 at 7:34

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.