Does anyone know how to use php’s flush(); function on a Wordpress site?

Asked

Viewed 213 times

1

Some time ago I posted this question because needed to run a script that pulled a lot of information (multiple requests) in Wordpress, searching a little found the function flush(); to be able to release the content gradually as the script was running.

The found example works perfectly if you use it on a page outside of Wordpress (even if inside the same server).

<?php

    for($i=1;$i<=10;$i++){
        echo 'processing...<br>';
        flush();
        sleep(1);
    }
?>

Performing some tests, I realized that the same script above does not work if it runs on a Wordpress page, for example:

function simple_function_2() {
    
    for($i=1;$i<=10;$i++){
        echo 'processing...<br>';
        flush();
        sleep(1);
    }
}

add_shortcode( 'own_shortcode2', 'simple_function_2' );

As an example in this question, the function must be added to the file functions.php and call on a Wordpress page with:

[own_shortcode2]

For some reason, the page will have the expected output:

processing...
processing...
processing...
processing...
processing...
processing...
processing...
processing...
processing...
processing...

But each of the words "Processing..." is not displayed every second, just like when the command is called on a page outside of Wordpress. If you try to run it, you will see that the page itself takes 10 seconds to complete the upload, and only then is displayed to the user.

I tried to find something on the internet reporting the problem, but I couldn’t get anywhere.

Is there any alternative to turn the flush(); on a Wordpress site?

1 answer

2


You can make the following change in the code:

function simple_function_2() {
    
    for($i=1;$i<=10;$i++){
        flush();
        echo str_pad("processing...<br>", 4096);
        sleep(1);
    }
}

add_shortcode( 'own_shortcode2', 'simple_function_2' );

Explaining the echo str_pad("processing...<br>", 4096);

  • Some browsers will not display content if it is too short

  • We use str_pad() to make the output long enough So you’ll be able to see the line-by-line execution on the screen.

Note: If your Worpress theme has any kind of preloader, you will need to disable!

Obs2: tested and works.

Source: PHP flush() Function

  • 1

    Thank you very much, it worked :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.