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

php - How to check if feed URL was requested?

programmeradmin1浏览0评论

I'm writing a plugin to block some pages to anonymous users on my site. I already blocked some pages but I can't get to identify the feed page my-wordpress-site/feed.

I've tried:

  • $GLOBALS['pagenow'] == 'feed'
  • is_feed()
  • is_page('feed')
  • checking on $_SERVER['REQUEST_URI'] and $_SERVER['PATH_INFO']

Any ideas on how to achieve that?

I'm writing a plugin to block some pages to anonymous users on my site. I already blocked some pages but I can't get to identify the feed page my-wordpress-site/feed.

I've tried:

  • $GLOBALS['pagenow'] == 'feed'
  • is_feed()
  • is_page('feed')
  • checking on $_SERVER['REQUEST_URI'] and $_SERVER['PATH_INFO']

Any ideas on how to achieve that?

Share Improve this question asked Sep 9, 2019 at 21:15 Rafael Carneiro de MoraesRafael Carneiro de Moraes 1038 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 7 +50

You have not specified exactly when your code runs but you can hook into "request" to check the requested page:

add_filter( 'request', function( $request ){
    if( isset( $request['feed'] ) ){
        //This is a feed request
    }
    return $request;
});

When the requested page is a feed $request, which is an array of query variables, will contain an item called "feed" which is set with the name of the feed like "rss" for example. https://codex.wordpress/Plugin_API/Filter_Reference/request

You're not specifying where you are hooking your action, but most likely you are hooking too soon, because is_feed should really do the trick. Let's take a look at the WordPress hook order.

As you can see the usual hook for plugins is init. However, at that point WP is not yet fully loaded. Only after the wp_loaded hook, WP starts processing the query. Because is_feed is a function of the $wp_query class it will not return true before this point.

So, you can still hook the main function of your plugin into init, but you must make sure that inside that function you add an action to a later hook. The most logical hook is template_redirect, because what you want is to serve a different (empty) page to some users. It would amount to this:

 [inside your plugins main function]
 add_action ('template_redirect','wpse346949_redirect_feed');

 [elsewhere in your plugin]
 function wpse346949_redirect_feed () {
   if (is_feed () && ( ... other conditions ... ) ) {
     wp_redirect (home_url ());
     die;
     }
   }

This will lead users to your homepage, but you can of course specify any other page, or even send them into the woods by not redirecting them at all and just cut off the page rendering.

发布评论

评论列表(0)

  1. 暂无评论