0

This code outputs the following warning when run on the pre_get_posts action:

Trying to get property of non-object

Which points to this line:

if( 'edit' == $screen->base && 'my_post_type' == $screen->post_type && $order_by == '0' ) {

Why am I getting this warning?

    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' );
        }

    }
1
  • Try dumping $screen and check what it contains at that point?
    – Rarst
    Commented May 22, 2017 at 15:51

1 Answer 1

2

$screen may not be available yet when pre_get_posts fires. Try this instead:

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');
    }
}
1
  • You're right, $screen is only available on the admin side, and the beginning of their pre_get_posts is telling it to run on non-admin pages.
    – Howdy_McGee
    Commented May 22, 2017 at 16:20

Your Answer

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

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