0

I am trying to order the post by a meta value but it is not working the right way.

I store the date in the post meta value like this 01 December 2019 10:00. Now I want to sort the posts desc or asc like the date.

I tried the following code:

$orderby = $query->get( 'orderby' );
            $sorting = $query->get( 'order' );

            if ('month' == $orderby ) {



                $query->set( 'meta_key', 'preferred_date' );
                $query->set( 'orderby', 'meta_value');
                $query->set( 'order', $sorting );

            }

I use the code in the action pre_get_posts.

Did anyone have some suggestions?

4
  • just set orderby to string of 'meta_value' as in this answer: wordpress.stackexchange.com/a/15499/76440 then you can set order to ASC or DESC
    – majick
    Commented Dec 18, 2019 at 11:52
  • This is not working
    – yfain
    Commented Dec 18, 2019 at 13:53
  • try posting the full code that you have now, otherwise no one will know your next step
    – majick
    Commented Dec 19, 2019 at 2:22
  • My full code now is: $orderby = $query->get( 'orderby' ); $sorting = $query->get( 'order' ); if ('month' == $orderby ) { $query->set( 'meta_key', 'preferred_date' ); $query->set( 'orderby', 'meta_value'); $query->set( 'order', $sorting ); }
    – yfain
    Commented Jan 3, 2020 at 9:31

1 Answer 1

1

The problem was that I have not stored the date values in the right way. I had to save it like Y-m-d or Y-m-d H:i

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.