Execute Code on Every Page Request in WordPress

I want to run some code on every page request in WordPress. I used the init and shutdown actions, but on one page it is calling the method twice somehow. Is there an alternative or better approach in PHP in WordPress.

Related posts

Leave a Reply

2 comments

  1. Mike, assuming that by page request you mean the front part of it (not including the admin hits) then wp_footer is the best place to add_action() to.

    Calling the method twice could mean a few things (off the top of my head):

    • The page you’re viewing fires an AJAX request which runs through the init action just like any other request.
    • The page you’re viewing is being redirected, that goes through the init action as well
    • There’s an element on the page causing it to refresh or firing a call to that page, Flash objects like to do that, especially games, Disqus commenting plugin likes to do that as well.

    To debug that you could try and output or log the contents of the $_REQUEST array to see why it’s being fired twice.

    Cheers.

  2. You can simply do that in the page.php file of your selected theme. That php code is executed for displaying each page. If you want to execute some code for posts then use single.php.