Wordpress - How to check if feed URL was requested?

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.org/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.

Tags:

Php

Feed

Pages

Urls