Sort Wordpress Posts by Custom Field
I do *A LOT* of query_posts in my WP Theming for work, and I’ve found a million-and-one reasons why I needed this bit-o’-code lately. Instead of having oh-so-blog-centric sortable options such as “By Title”, “By Category” “By Modified Time”, I needed to manually sort the posts in a given category. Why? Cuz I’ve got a list of posts in a category that needs to be sequential. Very non-bloggy, but VERY CMSy.
Solution: Just add this code in to each template & make sure the blog posts are in the category MYCATNAME with a custom tag of “order”, from 0 to ad infinitum.
<?php $posts=query_posts("category_name=OptionsPage&orderby=menu_order&order=asc");
$out_array=array();
//loop #1: get the post & attach post_meta 'order' to the menu_order
foreach($posts as $post){
$this_order=0;
if( strcmp(get_post_meta($post->ID, "order", true),"")!=0){
$this_order=get_post_meta($post->ID, "order", true);
}
$post->menu_order=$this_order;
if($out_array[$this_order]==null){//start the ordering (solved: if 2 have the same order!)
$out_array[$this_order]=$post;
} else {
array_push($out_array,$post);
}
}
//sort acc.to menu_order
$wp_query->posts=null;
$wp_query->posts=array();
for($i=0;$i<count($out_array)+1;$i++){
if($out_array[$i]!=null){
array_push($wp_query->posts,$out_array[$i]);
}
}
//start looping through!
$idx=0;
if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); $idx++;?>
<li class="flipmenuitem"><a id="link<? echo $idx; ?>" href="#" style="background:#FFF url(’<? echo bloginfo(’template_directory’);?>/images/<?if($idx==1){?>minus<?} else {?>plus<?}?>.gif’) no-repeat;padding-left:15px;" onclick="javascript:Effect.comboEffect0(’flip<? echo $idx; ?>’,this);"><?php the_title(); ?></a>
<div class="flippage" style="display:<?if($idx==1){?>block<?} else {?>none<?}?>;" id="flip<?echo $idx; ?>"><?php the_content(); ?></div></li>
<?php endwhile;
else :
endif; ?>
// … you get the picture here..
September 19th, 2008 |
I would love to see how this bit of code could be modified to sort posts by custom fields such as price, square feet, etc. Thank you!