0

I have lesson custom post types which have 4 date sub fields (among others): period_a_start, period_b_start, period_c_start, period_d_start.

I want to create a query to get the 8 first lessons that start sooner (ordered) (no matter which period starts sooner).

So if A lesson (period_c_start = 13.12.2018), B lesson (period_a_start = 20.12.2015), C lesson (period_d_start = 14.12.2018) .....

I want to get the lessons back ordered like this: A lesson, C lesson, B lesson ...

So this is what I have tried so far:

$args  = ['post_type'=> 'cp_course', 'numberposts' => 8,'orderby' => 'menuorder', 'order' => 'ASC',
         'meta_query' =>
            array(
                'relation' => 'OR',
                array(
                    'key' => 'period_a_start',
                    'compare' => '>=',
                    'type' => 'numeric',
                    'value' => date("m/d/Y"),
                ),
                array(
                    'key' => 'period_b_start',
                    'compare' => '>=',
                    'type' => 'numeric',
                    'value' => date("m/d/Y"),
                ),
                array(
                    'key' => 'period_c_start',
                    'compare' => '>=',
                    'type' => 'numeric',
                    'value' => date("m/d/Y"),
                ),
                array(
                    'key' => 'period_d_start',
                    'compare' => '>=',
                    'type' => 'numeric',
                    'value' => date("m/d/Y"),
                )
            )];
$course = get_posts($args);

But this approach doesn't guarantee that it will return the 8 lessons that start sooner ordered by date

0

I would advice you to store the time as a string instead of a d-m-Y format. Use strtotime() to format it as a long integer. This will help you comparing the strings. I'm not 100% sure if PHP is able to compare string dates. It is however able to compare timetamps as this user mentioned as well: How to compare dates and strings in PHP

2
  • That should be maybe a comment not an answer. It doesn't face the problem I face with ordering lessons. Thank you anyway
    – dvn22
    Dec 12 '18 at 10:11
  • I don't have enough rep. to comment, I can only post answers.
    – Jim
    Dec 12 '18 at 12:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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