在 send_headers 操作中获取 Wordpress 页面 slug

Get Wordpress page slug in send_headers action

我想在特定页面上发送带有 send_headers 操作的自定义 headers(禁用缓存),但无法访问页面 slug。 $post 变量似乎是空的。代码如下

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");
        }
    }

在这个钩子的时候我们还没有 $post 对象。

您可以通过从 URL 获取提示来执行某些操作,如下所示:

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

此外,您甚至可以查询 WP 数据库以获取更多信息,例如:

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

现在您有 $post 对象来提取您可能需要在 send_headers 挂钩期间发送的任何其他数据。