最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Hook to change HTTP response headers

programmeradmin1浏览0评论

I want to write a simple Wordpress plugin. The plugin will:

  1. Read (if set) a cookie from the visitor
  2. Send a cookie (if not set) to the visitor
  3. Depending on the cookie value I will redirect the user to a new pages

I found some documentation for getting/setting cookies through WP, and I'm guessing I can just issue a redirect from PHP. So I downloaded the WordPress Boilerplate (WPBP) code and so far so good. But I'm stuck at:

  1. Which WP callback should I hook into for my code? (init ?) I found the plugin documentation but I'm struggling to understand where this type of code should hook into.
  2. Should I put any of my code into the main/global portion of the WPBP file? Or only in the called back function.
  3. This plugin will run on a WP multisite installation. Does that mean my plugin code would run on every site? If so, how could I restrict my plugin code to run on only a particular site? (PHP check for a URI?)

I want to write a simple Wordpress plugin. The plugin will:

  1. Read (if set) a cookie from the visitor
  2. Send a cookie (if not set) to the visitor
  3. Depending on the cookie value I will redirect the user to a new pages

I found some documentation for getting/setting cookies through WP, and I'm guessing I can just issue a redirect from PHP. So I downloaded the WordPress Boilerplate (WPBP) code and so far so good. But I'm stuck at:

  1. Which WP callback should I hook into for my code? (init ?) I found the plugin documentation but I'm struggling to understand where this type of code should hook into.
  2. Should I put any of my code into the main/global portion of the WPBP file? Or only in the called back function.
  3. This plugin will run on a WP multisite installation. Does that mean my plugin code would run on every site? If so, how could I restrict my plugin code to run on only a particular site? (PHP check for a URI?)
Share Improve this question edited Sep 25, 2019 at 16:42 fuxia 107k39 gold badges255 silver badges459 bronze badges asked Sep 25, 2019 at 15:40 TSGTSG 1054 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

Your questions about how you should structure your plugin are somewhat too broad, but here is a specific answer to the title question.

To change headers before they’re sent, use the wp_headers filter.

function tsg_filter_headers( $headers ) 
{
    // For debug. This will break your page but you will see which headers are sent
    // print_r( $headers );

    // It’s a good idea to leave the admin alone
    if ( !is_admin() ) {

        // Add or redefine 'Content-Location' header
        $headers['Content-Location'] = '/my-receipts/42';
    }

    return $headers;     
}
add_filter( 'wp_headers', 'tsg_filter_headers' );

See the WordPress doc here.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论