PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, February 5, 2022

[FIXED] WordPress get terms and orderby

 February 05, 2022     php, taxonomy, wordpress     No comments   

Issue

I am querying the terms in a custom taxonomy i have with the following code:

<?php
  $term_slug    = get_query_var('term');
  $taxonomyName = get_query_var('taxonomy');
  $current_term = get_term_by('slug', $term_slug, $taxonomyName);
  $termchildren = get_term_children($current_term->term_id, $taxonomyName);
  foreach ($termchildren as $child) {
    $term = get_term_by('id', $child, $taxonomyName);
    
    echo '<li id="mid"><a href="#tab-' . $slug = $term->slug . '">' . $term->name . '</a></li>';
    
  }
?>

This is all working great! The problem I have is that I would like to order it by menu-order or something similar. At the moment they are in random order!

Can anyone suggest what I need to do?


Solution

Try to use get_terms function. Your code than would be like this (you can specifiy orderby and order arg)

<?php
  $term_slug     = get_query_var('term');
  $taxonomy_name = get_query_var('taxonomy');
  $current_term  = get_term_by('slug', $term_slug, $taxonomy_name);
  if ( true === is_a( $current_term, 'WP_Term' ) ) {
      $args = array(
          'child_of' => $current_term->term_id,
          'orderby'  => 'id',
          'order'    => 'DESC'
      );
      $terms = get_terms($taxonomyName, $args);
      if ( true === is_array( $terms ) ) {
          foreach ($terms as $term) {
              echo '<li id="mid"><a href="#tab-' . esc_attr( $term->slug ) . '">' . esc_html( $term->name ) . '</a></li>';
          }
      }
  }
?>


Answered By - david.binda
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing