Forums

query_posts not sorting "numeric" custom field as it should. Any help please? (5 posts)

  1. slobizman
    Member
    Posted 1 year ago #

    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    	$current_cat = get_query_var('cat');
    
    	$args=array(
    		'category__in' => array($current_cat),
                'posts_per_page' => -1,
    		  'paged' => $paged,
                'orderby' => meta_value,
                'meta_key' => reviews_sort,
                'order' => ASC
    	);
    
    	query_posts($args);

    The above is a portion of a function I have, and it's giving me fits. It is supposed to sort by the custom field "reviews_sort" and it's sort of, kind of, but not really.

    I am assigning values like 10, 20, 25, 30, 40, etc. I have the spacing in between so that I can insert new posts without renumbering them all.

    But the posts display "generally" in the right order. But not really right.

    I get a feeling that the problem is that the custom field is an alphanumeric field and I'm wanting to sort on numeric values. But since all of my numbers are two character (10-99), it still should work.

    Can anyone tell me how to make this work, please?

  2. Mark / t31os
    Moderator
    Posted 1 year ago #

    Try meta_value_num as the orderby paramter, as introduced in the 13501 changeset.

  3. slobizman
    Member
    Posted 1 year ago #

    Thanks Mark. It works. I just had found that with some searching, and was coming back to tell everyone about it, and saw your post. I guess it's yet undocumented. Wasn't easy to find.

  4. Mark / t31os
    Moderator
    Posted 1 year ago #

    Happy i could help, i've updated the codex page to reflect the new orderby parameter to... :)

  5. kolufild
    Member
    Posted 1 year ago #

    What about filtering the posts by custom field numericaly? Example:

    $prev_post = new WP_Query();
    $prev_post->query( array('cat' => $category_id,
    			 'meta_key' => '_my_order',
    			 'orderby' => 'meta_value_num',
    			 'order' => 'DESC',
    			 'meta_compare' => '<',
    			 'meta_value' => get_post_meta($post->ID, '_my_order', true),
    		)
    );

    First post in this query results should be the previous post by _my_order. But since comparison isn't done numerically, this gives wrong results.

Topic Closed

This topic has been closed to new replies.

About this Topic