0

I would like to sortable a column with custom data. I have a custom post type named "events" and I have a custom meta_key named "_start_at".

My column is sortable but when I click on, my posts are ordrered by date of publication and not by date "start_at".

How can i do this ?

This is my code :

function my_set_sortable_columns( $columns )
{
    $columns['dateevent'] = 'dateevent';
    return $columns;
}
add_filter( 'manage_edit-event_sortable_columns', 'my_set_sortable_columns' );

function my_sort_custom_column_query( $query )
{
    $orderby = $query->get( 'orderby' );

    if ( 'dateevent' == $orderby ) {

        $meta_query = array(
            'relation' => 'OR',
            array(
                'key' => '_start_at',
                'compare' => 'NOT EXISTS',
            ),
            array(
                'key' => '_start_at',
            ),
        );
        $query->set( 'meta_query', $meta_query );
        $query->set( 'orderby', '_start_at' );
    }
}
add_action( 'pre_get_posts', 'my_sort_custom_column_query' );

Here it's an example of data for the _start_at meta value : enter image description here

8
  • You need to assign _start_at as the array key for one of the arrays in your meta_query array. That's how we sort by a specific meta query clause.
    – Sally CJ
    Jul 19, 2022 at 9:22
  • I try to do this : '_start_at' => array('key'.... for the first and for the second array of meta_query array but it does not change anything...
    – Gpi
    Jul 19, 2022 at 11:35
  • What is the format of the start_at meta value? Can you give some sample values?
    – Sally CJ
    Jul 19, 2022 at 11:53
  • I added an example in my first message.Thanks a lot for your help
    – Gpi
    Jul 19, 2022 at 12:12
  • Well, I suggest you to change the format to a standard MySQL date format like Y-m-d H:i:s. Because otherwise, sorting the values won't be easy. Did you use a plugin to add the meta; if so, what plugin?
    – Sally CJ
    Jul 19, 2022 at 12:15

1 Answer 1

0

Thanks a lot to @Sally CJ for the answers. It works with changing format of start_at field and adding key in array like this :

function my_sort_custom_column_query( $query )
{
    $orderby = $query->get( 'orderby' );

    if ( 'dateevent' == $orderby ) {

        $meta_query = array(
            'relation' => 'OR',
            '_start_at' => array(
                'key' => '_start_at',
                'type' => 'DATETIME',
            ),
        );
        $query->set( 'meta_query', $meta_query );
        $query->set( 'orderby', '_start_at' );
    }
}
add_action( 'pre_get_posts', 'my_sort_custom_column_query' );

Your Answer

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

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