How to correctly detect accessing wp-content/uploads?

WordPress does not serve those files, when you request a PDF it’s Apache/Nginx that serves the file to the browser, no PHP is executed. This is a good thing as it’s much faster than PHP and saves a lot of server resources.

For this reason, your attempt won’t work, and no changes to the PHP will fix it.

I want to be able to know how often a user is accessing specific PDF files.

If you want to track views then you have these options:

  • embed the PDF in a page that you can track
  • put the PDF behind a paywall or button that you can track that redirects to the PDF

Note that browsers will cache the PDF, and that most browsers will provide download options when displaying PDFs. For this reason your stats will be unreliable. You may not be able to get the results you want out of an uploaded PDF.

Also, if someone shares a direct URL to the PDF it will not trigger any tracking.

The only other option, is to never share the URL to the PDF at all, and instead use a custom URL that retrieves and displays the URL using server headers. However this too can be saved by the browser, and can be cached ( or even printed to a new untraced PDF via the system print dialog ). It will also be slower and use much more server resources for minimal gain.