Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm using the following code to display data from subcategories. The subcategories are 'United kingdom', 'England Only', 'Northern Ireland Only', 'Scotland Only', 'Wales Only'.

Ordering by date or asc/desc puts the UK subcategory somewhere in the middle with either Wales or England at the top. I need the UK subcategory to be at the top. It holds the most posts - so is it possible to use an orderby in the query to fix this? Or do you think I need to create its own loop for the UK subcategory only?

$parentCatID = get_cat_ID('Grants and Incentives');
$childCats = get_categories( 'child_of='.$parentCatID.'&orderby=date&order=asc' );
if(is_array($childCats)):
foreach($childCats as $child){ ?>
<h2 class="experts <?php echo $child->name; ?>"><?php echo $child->name; ?> Grants and Incentives</h2>
<?php query_posts('cat='.$child->term_id.'&post_type=grants-and-incentive');
while(have_posts()): the_post(); $do_not_duplicate = $post->ID;

Edit: I'm now using the Category Order and Taxonomy Terms Order Plugin and orderby=term_order. Which works great. It would be good to know how this works without using a plugin though, if anyone could explain it!

share|improve this question

1 Answer 1

up vote 0 down vote accepted

I have never used the plugin you found but it looks pretty heavy, at least on the backend, and may be overkill unless you need a lot more functionality than described in the question.

get_categories operates from cached data so my thought was to simple alter the returned array rather than perform another query or a more complicated one.

function move_cat_to_top_wpse_107314($move, $cats = array()) {
  if (empty($move) || empty($cats)) {
    return false;
  }
  $cat = array_search($move,wp_list_pluck($cats,'slug'));
  if (false !== $cat) {
    $tmp = $cats[$cat];
    unset($cats[$cat]);
    array_unshift($cats,$tmp);
  }
  return $cats;
}

$parent = get_cat_ID('aciform');
$children = get_categories( 
  array( 
    'child_of' => $parent,
    'orderby' => 'date',
    'order' => 'asc',
  )
);
// var_dump($children);
var_dump(move_cat_to_top_wpse_107314('sub', $children));

The move_cat_to_top_wpse_107314 function is all you need. The rest illustrates usage and works with data on my sandbox site.

Also, please don't use query_posts.

share|improve this answer
    
Thanks - this is great. Exactly what I needed. –  Dave Jul 22 '13 at 9:01

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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