• Resolved eastgate

    (@eastgate)


    I’ve found what I think may be an issue in the plugin. I’ve got some code on my frontend to render templates, which calls get_lazysizes_html() and normally works just fine. However, when I have the same templates set up to load through an ajax call using WordPress’s standard admin-ajax.php, I get a fatal PHP error like this:

    PHP Fatal error: Uncaught Error: Call to a member function preg_replace_html() on null in /<filepath>/class-lazysizes.php:279

    I found that the global $lazysizes object is not being initialized correctly because is_admin() is returning true when calling get_lazysizes_html() via admin-ajax.php, even though the code is being used to render a template on the frontend. This is happening on line 49 in class-lazysizes.php:

    if ( is_admin() ) {

    If I change this to the following, it works:

    if ( is_admin() && ! wp_doing_ajax() ) {

    Would it make sense for you to change this in the plugin, or is there a workaround I’m missing?

Viewing 5 replies - 1 through 5 (of 5 total)
  • Plugin Author Patrick Sletvold

    (@16patsle)

    Hi,
    That definitely seems like an issue, yes. Seems like the plugin is attempting to set up the settings page, even when running ajax. Fixing it in the plugin would be ideal. Do you happen to know if the solution you suggest could lead to any other issues? Nothing comes to mind for me.

    As an alternative solution I could of course add some global flag/filter to override the is_admin check, but fixing it properly would be best.

    – Patrick Sletvold

    Thread Starter eastgate

    (@eastgate)

    Thanks for the reply. It seems to be the recommended solution when I did a search for issues with admin-ajax.php and is_admin(). WordPress is a little weird how the recommended way to do ajax calls on the frontend is through an admin script!

    I’m not sure if there might be a case where you could be using ajax within the admin and it could cause a problem?

    Plugin Author Patrick Sletvold

    (@16patsle)

    I think I’m just gonna try to implement your fix and see what happens. There probably shouldn’t be any ajax calls that need the settings page loaded anyways, so I’m willing to take that risk. I’ll do some tests, and probably ship it in the next patch release.

    – Patrick Sletvold

    Thread Starter eastgate

    (@eastgate)

    Sounds great. Thanks, Patrick!

    Plugin Author Patrick Sletvold

    (@16patsle)

    Slightly bigger release than I anticipated, since I put in a couple more fixes and changes. But at least your issue should be fixed now. Don’t hesitate to get back to me if anything else comes up though.

    – Patrick Sletvold

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Fatal error when calling the plugin from ajax functions (admin-ajax.php)’ is closed to new replies.