I am trying to find a hook to be able to set a datalayer.push everytime a document is opened.
It could even be something that runs after the document is opened ex: https://proximite-courtage.fr/wp-content/uploads/2022/06/LISTE_PARTENAIRES_PC_22062022.pdf
WP isn’t running when you visit PDF files directly via their URL, so there is no PHP loaded and no opportunities for WordPress hooks
Does it exist? Or how can I create one?
In the olden days the
wp-content/uploads folder was handled by an
ms-files.php, which might have provided you this possibility in some cases. However it had large performance problems, is incompatible with a lot of CDNs and caching systems.
Most importantly of all:
- it would only work the first time due to browser cache
- it’s deprecated and only present for legacy reasons.
If you did use this, and worked around the problems, the resulting hook would be extremely unreliable.
If you want to fire off an analytics event when a user visits and opens a PDF you have these options:
- you need to indicate the PDF can never be cached in the headers
- you need to handle the loading and sending of the PDF yourself
- you’ll need special Apache/Nginx rules to reroute the request to your custom bespoke application ( highly likely that this will not be a WordPress application )
- you would need to investigate options for the PDF phoning home, as well as the legal and regulatory ramifications, as anybody could save and share the PDF
- all these protections can be bypassed using the print dialog, either to physical paper, or the print to PDF option
The easiest option is to never link to the PDF and instead display it inside the web page.
But most important of all, you need to come to terms with the fact that no matter what you do, no matter what system you use, you will never get a reliable analytics signal that your PDF was opened, and you will always record fewer openings than actually happened.