Customize Posts Order in WordPress via Custom Fields
July 23rd, 2009Who Said WordPress Isn't Flexible Enough?

I came across this last night, might be helpful for some of you ;) Sorting posts in a customized order is pretty simple with the WordPress custom fields mechanism and custom SQL queries. Start off with a basic query:
$querystr = " SELECT wposts.* FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta WHERE wposts.ID = wpostmeta.post_id AND wpostmeta.meta_key = 'order' AND wposts.post_type = 'post' AND wposts.post_status = 'publish' ORDER BY wpostmeta.meta_value ASC ";
That will sort the posts in ascending order using the custom field called order. This is how you actually process the query and get into The Loop:
$pageposts = $wpdb->get_results($querystr, OBJECT); if ($pageposts) { foreach ($pageposts as $post) { setup_postdata($post); // you can use template tags from now on } }
One more thing. How to use more than one custom field in your query? Well, yes, this is SQL, not WordPress, but anyways. Let’s say you want to select all the posts marked complete (custom field) and sorted by order (another custom field). Here you go:
SELECT wposts.* FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta, $wpdb->postmeta wpostmeta2 WHERE wposts.ID = wpostmeta.post_id AND wposts.ID = wpostmeta2.post_id AND wpostmeta.meta_key = 'order' AND wpostmeta2.meta_key = 'complete' AND wpostmeta2.meta_value = '1' AND wposts.post_type = 'post' AND wposts.post_status = 'publish' ORDER BY wpostmeta.meta_value ASC
Assuming the complete custom field takes a 1 when the post is complete. I used this method in a simple task manager theme I did for WordPress. Did I overuse the word “custom”? ;)
Related posts:
- WordPress: Tag Cloud Based on Author Posts
- The WP-Custom plugin. What’s it all about?
- The Facebook Platform: Building a Custom Fan Page
- WordPress: Recent Comments by Category
Tagged: snippets, sql, wordpress
Shortlink: http://kovshenin.com/1049














Привет, а где этот код должен быть? Внутри лупа?
я использую вот такой способ, и как видишь не могу сделать сортировку по другому филду.
$recent = new WP_Query(“meta_key=custom&orderby=meta_value&cat=$categ&order=ASC&showposts=8″);
Нет, он должен быть ДО the_loop .. Через WP_Query вряд ли получится поработать с одним, и уж тем более несколькими custom полями, поэтому нужен custom SQL запрос.. В общем вот это вот $recent = new … ни к чему. Попробуй как в моём примере.
привет
у меня какой-то непонятный затык с подобной выборкой. не подскажешь?
пытаюсь выбрать посты со значением Y в поле _author_column и отсортировать их по значению поля _number_to_show
$querystr = ”
SELECT wposts.*
FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta, $wpdb->postmeta wpostmeta2
WHERE wposts.ID = wpostmeta.post_id
AND wposts.ID = wpostmeta2.post_id
AND wpostmeta.meta_key = ‘_number_2show’
AND wpostmeta2.meta_key = ‘_author_column’
AND wpostmeta2.meta_value = ‘Y’
AND wposts.post_type = ‘post’
AND wposts.post_status = ‘publish’
ORDER BY wpostmeta.meta_value ASC”;
$pageposts = $wpdb->get_results($querystr, OBJECT);
var_dump($pageposts);
Получаю непонятно что. Вернее ничего не получаю во-об-ще. Посты на месте, поля заполнены. Почему может не срабатывать выборка по custom fields?
Спасибо за ответ. Заранее
простите идиота, если отнял время
забыл объявить $wpdb
Именно :) надеюсь проблема решена.