1

The following bit of code was used in my fictitious plugin to redirect the non-logged in users from page 173 (ID) to sample-page (slug). The code's working good. But just today, I figured out that the code is causing Notices in Firefox.

The issue happened when I tried setting a Static Page as the front page from Settings > Reading.

Notice: Trying to get property of non-object in /wp-includes/class-wp-query.php on line 3760

Notice: Trying to get property of non-object in /wp-includes/class-wp-query.php on line 3762

Notice: Trying to get property of non-object in /wp-includes/class-wp-query.php on line 3764

With several inspection I figured out that, the following bit of code is causing the issue. And to be specific the issue is with the is_page(173).

add_action('pre_get_posts', function($query) {
  if( $query->is_main_query() && ! is_admin() && ! is_user_logged_in() && $query->is_page(173) ) {
    wp_redirect(home_url('/sample-page'));
    exit();
  }
});

I tried changing from $query->is_page(173) to is_page(173) - the result is same.

To test in a blank installation, I tried disabling all the plugins and set the default theme TwentySixteen, and Re-installed WordPress to get a fresh install. I put the following code in TwentySixteen's functions.php, and with DEBUG on, here's what I got. (The notice is under the black area of header, just hit Ctrl + A to see 'em) You can check the redirection is working from this page (173) to this page without any Notice.

What's the problem with my code?

  • What context is your hook being called from? Might be worth simplifying it for the sake of troubleshooting by creating a named function instead of a closure. – Chris Cox Jul 14 '17 at 15:47
  • @ChrisCox I'm afraid can't get you. I explained my context - redirecting non-logged-in users from one page to another. Anyway, I named it now on the live link. – Mayeenul Islam Jul 14 '17 at 16:27
  • By context, I mean is it in the global scope or in a class method? – Chris Cox Jul 14 '17 at 16:41
  • If you look at the lines it calls out in source, it's trying to read some properties from what it assumes is a page object, but in this case it's not. I'll guess that you can't check if it's a specific page before the query is run if it is in fact not a page at all. If you think about it, it's strange that it would work at all considering you're checking what it is pre getting the object. – Milo Jul 14 '17 at 16:46
  • 1
    This is related – birgire Jul 14 '17 at 17:10
0

Turn off debug mode and it will be gone, at least worked for me. I know it's an old post but just want to help people with the same issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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