custom sortable column

I fixed this issue by changing some of my code.

I changed:

add_filter( 'request', 'timeline_column_orderby' );


function timeline_column_orderby( $vars ) {
          if ( !isset( $vars['orderby'] ) || ( isset( $vars['orderby'] ) && 'Year' == $vars['orderby'] ) ) {
            $vars = array_merge( $vars, array(
                'meta_key' => 'timeline_date',


                  'orderby' => 'meta_value'
                ) );
            }
            return $vars;
 }

to:

add_action( 'load-edit.php', 'sort_year_load' );

function sort_year_load() {
    add_filter( 'request', 'sort_year' );
}

//make the date column sortable by year
function sort_year( $vars ) {

    /* Check if we're viewing the 'maryg_timeline' post type. */
    if ( isset( $vars['post_type'] ) && 'maryg_timeline' == $vars['post_type'] ) {

        /* Check if 'orderby' is set to 'year'. */
        if ( isset( $vars['orderby'] ) && 'Year' == $vars['orderby'] ) {

            /* Merge the query vars with our custom variables. */
            $vars = array_merge(
                $vars,
                array(
                    'meta_key' => 'timeline_date',
                    'orderby' => 'meta_value_num'
                )
            );
        }
    }

    return $vars;
}

Which told WordPress how to sort the table when I click on the clickable table header.

What I am doing is only run my customization on the edit.php page in the admin.

I then check if we’re viewing the correct custom post and also if it is set to year. Then I just order it by the meta_key.

My main issue I had was ordering the table on load. I fixed that with this code:

function set_year_post_type_admin_order($wp_query) {
    if (is_admin()) {
        $post_type = $wp_query->query['post_type'];

        if ( $post_type == 'maryg_timeline') {
            $wp_query->set('meta_key', 'timeline_date');
            $wp_query->set('orderby', 'meta_value_num');
            $wp_query->set('order', 'DESC');
        }
    }
}

add_filter ( 'pre_get_posts', 'set_year_post_type_admin_order' );

Which checks if your an admin and the post type and then sets the query to the values I set.

Hope this might help someone else if they come across it

Leave a Comment