I am trying to create a extra column for year in my timeline custom post. I can create the extra column and I can actually get it sorting and it works correctly but then all my pages then dont seem to work.
this is all of my code i am using to create the column and make it sortable:
// Register the column
add_filter( 'manage_edit-maryg_timeline_columns', 'set_custom_edit_date_columns' );
add_action( 'manage_maryg_timeline_posts_custom_column' , 'custom_date_column', 10, 2 );
function set_custom_edit_date_columns($columns) {
unset( $columns['date'] );
$columns['timeline_date'] = __( 'Year', 'your_text_domain' );
return $columns;
}
//output data for the column
function custom_date_column( $column, $post_id ) {
switch ( $column ) {
case 'timeline_date' :
$year = get_post_meta( $post_id, 'timeline_date', true );
if ( is_string( $year ) )
echo $year;
else
echo 'Unable to retrieve year';
break;
}
}
//make columns sortable
add_filter("manage_edit-maryg_timeline_sortable_columns", 'timeline_sort');
function timeline_sort($columns) {
// $custom = array(
// 'timeline_date' => 'Year'
// );
// return wp_parse_args($custom, $columns);
//or this way
$columns['timeline_date'] = 'Year';
return $columns;
}
//make the date column sorted by year by default
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;
}
the problem code i have narrowed it down to is:
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;
}
The only thing is i dont understand why my pages not work any more
Thanks in advance
EDIT
I’ve narrowed it down even further to it being this line of code:
!isset( $vars['orderby'] ) ||
but what im trying to do is sort by this column automatically and if i remove that it doesnt do that
I fixed this issue by changing some of my code.
I changed:
to:
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:
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