I'm doing some testing as I'm new to PHP and Wordpress.
On refresh the following code runs functions.php
<?php
$content = "some text here\n";
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/wp-content/themes/zerif-lite-child/myText.txt","a");
fwrite($fp,$content);
fclose($fp);
?>
Which writes to the .txt file multiple times! If I use "wb" it will write to the file only once, but I want this code to append the file, not overwrite it everytime.
I've tried using flock() but that produces the same result.
Why is it writing to this file multiple times when I append it?
I'm doing some testing as I'm new to PHP and Wordpress.
On refresh the following code runs functions.php
<?php
$content = "some text here\n";
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/wp-content/themes/zerif-lite-child/myText.txt","a");
fwrite($fp,$content);
fclose($fp);
?>
Which writes to the .txt file multiple times! If I use "wb" it will write to the file only once, but I want this code to append the file, not overwrite it everytime.
I've tried using flock() but that produces the same result.
Why is it writing to this file multiple times when I append it?
Share Improve this question asked Sep 28, 2015 at 11:04 user81086user81086 112 bronze badges 5 |1 Answer
Reset to default 1You could try putting your code in a WordPress Action or Filter call:
add_action( 'init', 'my_file_function' );
function my_file_function() {
$content = "some text here\n";
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/wp-content/themes/zerif-lite-child/myText.txt","a");
fwrite($fp,$content);
fclose($fp);
}
The flag ('a' vs 'wb') doesn't have anything to do with your problem, it just happens to showcase it. For whatever reason, your functinos.php
seems to be running more than once. You could start with a fresh copy of the default theme and try your code again, but you should also get in the habit of writing your code inside of an action call.
This helps ensure that the code you want to run is running at the appropriate time. It also allows you to hook in to various places in WordPress and generally makes coding for it much more powerful.
file_put_contents()
withFILE_APPEND
flag? Edit: Sorry, misunderstood, appending isn't the problem.. Put you code into a function and hook it to e.g.wp_loaded
. So some thing like:add_action( 'wp_loaded', 'write_to_file_function' ); function write_to_file_function() { //your code }
– Nicolai Grossherr Commented Sep 28, 2015 at 12:00functions.php
's? Because they will both get loaded, which would explain the multiple times execution. – Nicolai Grossherr Commented Sep 28, 2015 at 12:17wb
is probably doing the same thing, you just can't tell because the file is overwritten every time. – s_ha_dum Commented Sep 28, 2015 at 14:37