Question

I have added a custom field to some posts called 'frontpagerank' The plan is to order the posts by this value but first I just want to filter out any that don't use a front page rank. I have achieved this by putting the relevant posts into another array. But what to do next?

Also tried a query: $the_query = new WP_Query(array( 'meta_key' => '0', 'meta_value' => '44' ));

while ($the_query->have_posts()) : $query->the_post(); $count++;

This just does nothing. This code is hard to debug!

Was it helpful?

Solution

I have added a custom field to some posts called 'frontpagerank'

Then shouldn't the WP_Query args reference that key then, eg.

'meta_key' => 'frontpagerank'

If i follow, you want to check for posts that have this key, and you're expecting a numeric value, so i'll naturally assume you don't want posts with this key(but an empty value).

$the_query = new WP_Query(array( 'meta_key' => 'frontpagerank', 'meta_value' => '', 'meta_compare' => '!=', 'orderby' => 'meta_value_num' ));

Or if you specifically want to check for posts with that meta_key where the value is above say 0, you could do..

$the_query = new WP_Query(array( 'meta_key' => 'frontpagerank', 'meta_value' => '0', 'meta_compare' => '>', 'orderby' => 'meta_value_num' ));

You can read info on the meta parameters here.
http://codex.wordpress.org/Function_Reference/query_posts#Custom_Field_Parameters

Info on order by to, since i added that into the above to.. ;)
http://codex.wordpress.org/Function_Reference/query_posts#Order_.26_Orderby_Parameters

..any parameters you see listed for query_posts can be used inside WP_Query

Then all you need do is loop over that data like you had earlier..

// Note i made the correction you commented on, yes that's need to match
while( $the_query->have_posts() ) : $the_query->the_post();

   // do whatever

endwhile;

Hope that helps.

OTHER TIPS

Haven't tried it, but this seems like it should work:

$recent = new WP_Query("meta_key=your-custom-field&orderby=meta_value");
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top