0

The function is_user_logged_in() is not available at shutdown (plugin context, not theme).

I want my plugin to run only (1) on front-end pages and (2) when the user is not logged in.

This works, but since it also runs on Divi builder front-end pages, I need to add !is_user_logged_in:

if (!is_admin()) {
    add_action('shutdown', function () {
        // Do some ob_start() and PHP_Tidy() stuff...
    }, 0);
}

Unfortunately changing my conditional to if (!is_admin() && !is_user_logged_in()) fails with:

Uncaught Error: Call to undefined function is_user_logged_in() in...

Edit User Patrice says below that shutdown is too early to check for is_user_logged_in(). How could that could be? Shutdown is the last hook fired: Before PHP execution is about to end

Reference

2
  • 1
    Please note that is_user_logged_in is a pluggable function and you could get a fatal error if you call it too early. To solve this problem, you can wrap the login check within a function hooked to the init action. Please check this comment in the Codex : developer.wordpress.org/reference/functions/is_user_logged_in/… Commented Apr 18, 2023 at 19:27
  • Thanks Patrice, but I need my action to run at shutdown. Is that too early?
    – Jeff
    Commented Apr 18, 2023 at 20:59

1 Answer 1

0

Edit 1 - Does not work

// Catch is_user_logged_in() value before shutdown

function is_user_logged_in_init() {
    $is_user_logged_in_init = is_user_logged_in() ?? false;
}
add_action('init', 'is_user_logged_in_init');

Leaving this here for my reference. Ref

Edit 2 - Works

I found two ways to solve this:

  1. Option 1 - Not recommended Ref

include_once ABSPATH.'wp-includes/pluggable.php';

  1. Option 2 - Rewrite the script, i.e. Add shutdown action inside init action
function beautify_conditionals() {
    if (!is_admin() && !is_user_logged_in()) {
        add_action('shutdown', 'beautify_actions', 0);

        ob_start();
    }
}
add_action('init', 'beautify_conditionals');

function beautify_actions() {
    $html = ob_get_clean();

    $tidy = new tidy;
    $tidy->parseString($html, [
        'drop-empty-elements' => false,
        'drop-empty-paras' => false,
        'escape-scripts' => false,
        'fix-backslash' => false,
        'fix-style-tags' => false,
        'fix-uri' => false,
        'indent' => true,
        'indent-spaces' => 4,
        'join-styles' => false,
        'lower-literals' => false,
        'tab-size' => 4,
        'tidy-mark' => false,
        'wrap' => 0,
    ], 'utf8');
    $tidy->cleanRepair();

    $tidy = preg_replace('/<!DOCTYPE html>/', '<!doctype html>', $tidy);

    echo $tidy;
}

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.