Can I use a WordPress hook to create files, as my current setup seems to be failing?

Viewed 22

I want to create a new file every time a post is saved. I believe I can do this with the save_post() hook. I have managed to get the code below working outside the hook but when I try and add it to the Hook it doesn't generate the file.

Just for some context, I'm using DOMPDF to generate a pdf file but I think the issue is with creating the files on the last couple of lines rather than DOMPDF itself

require __DIR__ . "/vendor/autoload.php";
use Dompdf\Dompdf;
use Dompdf\Options;

function generate_pdf($post_id) {
  /**
   * Set the Dompdf options
   */
  $options = new Options;
  $options->setChroot(__DIR__);
  $options->setIsRemoteEnabled(true);

  $dompdf = new Dompdf($options);
  
  /**
   * Set the paper size and orientation
   */
  $dompdf->setPaper("A4", "portrait");
  /**
   * Load the HTML and replace placeholders with values from the form
   */
  $html = file_get_contents("template.html");

  $dompdf->loadHtml($html);
  /**
   * Create the PDF and set attributes
   */
  $dompdf->render();

  $dompdf->addInfo("Title", 'test'); // "add_info" in earlier versions of Dompdf

  /**
   * Save the PDF file locally
   */
  $output = $dompdf->output();
  file_put_contents('test.pdf', $output); 
  $myfile = fopen("testfile.txt", "w");
}

add_action( 'save_post_products',  'generate_pdf', 100, 2 );

You can see the last two lines where I'm trying to inject the file into the same directory. The last line is simply a test to see if any file will upload.

I'm working locally & the code is being generated from a custom plugin folder.

I'm not sure if it's an issue with the hook, permissions, or something else. I'm not even entirely sure about the best way to try and debug it as I'm more of a frontend developer. Any help would be massively appreciated.

1 Answers

it's not save_post_products you have extra (s)

it's save_post_product, fix your action name.

Related