• In resolved topic 203210 Mattifesto said that inserting the following code before the first call to have_posts() in archive.php would sort the posts by a custom field (‘popularity’ in the example, of course).

    query_posts(‘&meta_key=popularity&orderby=meta_value’);

    I’ve attempted to do this but am clearly inserting the code in the wrong place as it either appears on the published page or causes a PHP error.

    I’d be very grateful if someone could show me exactly where I should place the code in the following, from the existing archive.php.

    <?php get_header(); ?>

    <div id=”content”>

    <div id=”contentleft”>

    <div class=”postarea”>

    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>

Viewing 7 replies - 1 through 7 (of 7 total)
  • Right before if(have_posts())

    <?php query_posts($query_string . '&meta_key=popularity&orderby=meta_value');  if (have_posts()) : while (have_posts()) : the_post(); ?>
    Thread Starter joezy

    (@joezy)

    Many thanks for that. I’ve tried inserting the revised code on my archive.php template and it changes the order, but isn’t sorting them by the numerical value of the custom key (see ‘size’ below). Any thoughts on where I’m going wrong?

    It now looks like this:

    <div id="contentleft">
    
    		<div class="postarea">
    
    <?php query_posts($query_string . 'meta_key=size&orderby=meta_value');  if (have_posts()) : while (have_posts()) : the_post(); ?>
    
                <h1><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></h1>
    
                <?php the_content(__('Read more'));?><div style="clear:both;margin-bottom:30px;"></div>
    
    			<?php endwhile; else: ?>

    It might be sorting the meta_value as if it were a string.

    Thread Starter joezy

    (@joezy)

    OK thanks again, is there anything I can do about that? So far as I can see there’s no option in the custom fields part of a post to specify the type of data that’s in the field.

    Up till now I used the WP Smart Sort plugin to sort the posts. It no longer works with 2.8 but it included an option to specify the type of data.

    OK thanks again, is there anything I can do about that?

    I’d have to look into that. The ‘meta_value’ field is a longtext so it isn’t surprising that it would treated as a string. Does something like query_posts($query_string . 'meta_key=size&orderby=meta_value+0' work, by any chance?

    Thread Starter joezy

    (@joezy)

    Thanks for the suggestion, but I tried it and it didn’t. Any other ideas would be very welcome indeed!

    Yeah, I was afraid it wouldn’t work. Worth a shot though. You might have to do something like what is discussed here.

Viewing 7 replies - 1 through 7 (of 7 total)
  • The topic ‘Sorting posts by custom field – where to add code’ is closed to new replies.