0

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?

  • Trying to clarify: How many lines do you get if you refresh once? – Aravona Sep 28 '15 at 11:09
  • 1
    Have you tried using the WP File system API? What're you trying to do? Are you trying to create an error/debug log? – Tom J Nowell Sep 28 '15 at 11:52
  • Or file_put_contents() with FILE_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 Sep 28 '15 at 12:00
  • Are you using a parent-child-theme-combination? And if so, do you have the code in both functions.php's? Because they will both get loaded, which would explain the multiple times execution. – Nicolai Sep 28 '15 at 12:17
  • @ialocin is on the right track. Something about your implementation is causing the code the run multiple times. Using wb is probably doing the same thing, you just can't tell because the file is overwritten every time. – s_ha_dum Sep 28 '15 at 14:37
1

You 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.

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.