Search code examples
wordpressheadercache-control

Get Wordpress page slug in send_headers action


I want to send custom headers (disable cache) with send_headers action on a specific page but cannot access the page slug. The $post variable seems to be empty. The code is as follows.

add_action('send_headers', 'add_header_came');

function add_header_came() {
        global $post;
        if($post->post_name == 'page1' || $post->post_name == 'page2') {
            header("Cache-Control: no-cache, must-revalidate");
            header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
        }
    }

Solution

  • At the time of this hook we do not have $post object yet.

    You can do something from by getting hint from the URL , like following:

    $path_slug = pathinfo($_SERVER['REQUEST_URI'])['filename'];
    

    Also then you can even Query WP database for any more info like:

    if($path_slug != '' ):
      $args=array(
        'name'           => $path_slug,
        'post_type'      => array('post','page'),
        'post_status'    => 'publish',
        'posts_per_page' => 1
      );
      $post = get_posts( $args);
    

    Now you have $post object to extract any other data you may need to use to send during send_headers hook.