在上运行时,此代码输出以下警告pre_get_posts
措施:
Trying to get property of non-object
指向这条线:
if( \'edit\' == $screen->base && \'my_post_type\' == $screen->post_type && $order_by == \'0\' ) {
为什么我会收到这个警告?
public function my_post_type_default_sort( $query ){
if( !is_admin() ) {
return;
}
$screen = get_current_screen();
if( !isset( $_GET[\'orderby\'] ) ) {
$order_by = \'0\';
}
if( \'edit\' == $screen->base && \'my_post_type\' == $screen->post_type && $order_by == \'0\' ) {
$query->set( \'orderby\', \'scr_date\' );
$query->set( \'order\', \'ASC\' );
}
}
最合适的回答,由SO网友:WebElaine 整理而成
$screen
可能还不可用pre_get_posts
火灾。请尝试以下操作:
public function my_post_type_default_sort( $query ){
if(!isset($_GET[\'orderby\']) && is_admin()) {
$orderby = \'0\';
}
if($query->is_main_query() && is_admin() && is_post_type_archive(\'my_post_type\') && $orderby=0) {
$query->set(\'orderby\',\'scr_date\');
$query->set(\'order\', \'ASC\');
}
}