0

I want to order by post to check for the existence of a meta key ('featured') and include those posts first and as a secondary option I want to sort by post_date, similar to 'sticky' posts on a discussion forum.

I first tried this straightforward method ...

$args = array(
  'store'         => 'walmart',
  'post_type'     => 'post',
  'showposts'     => '-1',
  'orderby'       => 'featured date',
  'order'         => 'desc',
  'meta_key'      => 'featured'
);

It almost worked but instead of having the 'featured' posts at the top of the order it had them at the bottom, and no simple toggling could get it to work.

I then researched some more and came across this method http://dotnordic.se/sorting-wordpress-posts-by-several-numeric-custom-fields/, but I can't get this to work for the life of me. I would prefer to use this filter as I have one other customization that this might help with, can anybody show me what I'm doing wrong.

Here's what I have now ...

add_filter('posts_orderby','customorderby');
$args = array(
    'store'         => 'walmart',
    'post_type'     => 'post',
    'showposts'     => '-1',
    'meta_key'      => 'featured',
    'meta_query'    => array(
        array(
            'key' => 'featured'
        )
    )
);

$query = new WP_Query($args);
remove_filter('posts_orderby','customorderby');

and in my functions.php

add_filter('posts_orderby','customorderby');
function customorderby($arg) {
    global $wpdb;

    $arg = 'mt1.meta_value DESC, post_date+0 DESC';
    return $arg;
}
2
  • 1
    I think that you have a functional duplicate of this question: wordpress.stackexchange.com/q/103181/21376
    – s_ha_dum
    Commented Apr 22, 2014 at 16:55
  • Wow thats just what I needed. The $GLOBALS['wp_query']->request was very helpful in the OP's post too. Thanks!
    – Ryan Grush
    Commented Apr 22, 2014 at 17:50

0

Browse other questions tagged or ask your own question.