Support

Account

Home Forums General Issues Order get_terms by ACF field, even if the field is not set

Solving

Order get_terms by ACF field, even if the field is not set

  • Hello everyone.

    I added a custom field (order_by) for the category term.
    The categorys have a parent and are listed seperatly by the parents:

    Main Cat 1
    – Sub Cat 1 (order_by = )
    – Sub Cat 2 (order_by = )
    – Sub Cat 3 (order_by = )
    – …
    (should be sorted by “name” because order_by is not set)

    Main Cat 2
    – Morning (order_by = 1)
    – Afternoon (order_by = 2)
    – Evening (order_by = 3)
    (should be sorted by “order_by”)

    The problem
    If I fetch the terms with the meta_key “order_by”, I only get the terms that have an order_by value. The subcats from Main Cat 1 are not displayed.

    'hide_empty'  => false,
    'child_of' => $value->term_id,
    'meta_key'      => 'order_by',
    'meta_compare'  => 'NUMERIC',
    'orderby'       => 'meta_value_num',
    'order'         => 'ASC',

    Any idea to make that happen?

    Thanks 🙂

  • Does anyone have any ideas?
    I haven’t made any progress yet, unfortunately.

  • I recently built something similar

    This is my usort function for ordering terms

    
    function sort_vid_terms_by_menu_order($a, $b) {
      if ($a->sort_order == $b->sort_order) {
        return 0;
      } elseif ($a->sort_order < $b->sort_order) {
        return -1;
      } else {
        return 1;
      }
    } // end function sort_terms_by_menu_order
    

    and this is how I get the terms

    
    $args = array(
      'taxonomy' => $taxonomy,
      'hide_empty' => true,
      'parent' => $parent,
      'hierarchical' => true
    );
    $terms = get_terms($args);
    if (!empty($terms)) {
      foreach ($terms as $index => $term) {
        $term->sort_order = intval(get_field('sidebar_menu_order', $term));
      }
      usort($terms, 'sort_vid_terms_by_menu_order');
    }
    
Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.