Use repeatable Meta Box field for query orderby

Support General Use repeatable Meta Box field for query orderby

Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #2649
    MemaddogMemaddog
    Participant

    I have a custom post type for events. I am using the Meta Box date/time field and have it set to "clone" so I can add multiple event times (for events that take place on more than one day). Since that field now contains an array, my custom WP_Query isn't sorting the results using that meta_key. I originally had created this with a single date/time field (not able to clone) so the sorting worked perfectly.

    How can I modify my query args (below) to use the first item in the array for the orderby value?

    'meta_key' => 'event_start',
    'orderby' => 'meta_value',
    'order' => 'ASC',

    Thank you.

    #2661
    Anh TranAnh Tran
    Keymaster

    Hi,

    I'm afraid we couldn't make it work simply by modifying query arguments. Since the values are stored in a serialized array in the database, the sorting simply can't work.

    I suggest a hack for this: when saving the event times (array), save the first value into another custom field and use that new field for sorting.

    Here is a sample code, you should adapt it to your situation:

    add_action( 'rwmb_{META_BOX_ID}_after_save_post', 'prefix_add_event_start' );
    function prefix_add_event_start( $post_id ) {
        $times = get_post_meta( $post_id, 'event_start', true );
        if ( !empty( $times ) && is_array( $times ) ) {
            $start = reset( $times );
            update_post_meta( $post_id, 'event_start_first', $start );
        }
    }

    And then modify the query arguments by:

    'meta_key' => 'event_start_first',
    'orderby' => 'meta_value',
    'order' => 'ASC',
    #2663
    MemaddogMemaddog
    Participant

    I understand. I'm most certainly a novice so I wanted to ask. I was thrilled to hear your work-around as it is what I came up with as well.

    #2664
    Anh TranAnh Tran
    Keymaster

    That's the only way I can come up with. I think the solution is quite good for now 😉

Viewing 4 posts - 1 through 4 (of 4 total)
  • The topic ‘Use repeatable Meta Box field for query orderby’ is closed to new replies.