WordPress: if (url is example.com/sitemap) do this…

Previously, I’ve been creating my sitemap page with example.com?action=sitemap

That allowed me to easily test on my index page for a sitemap request with…

Read More
$_REQUEST['action']

However, I’d like to instead create the link to the sitemap with example.com/sitemap

And I’d like to know how I can parse the request for the appearance of “/sitemap

Related posts

Leave a Reply

5 comments

  1. You can create a new rewrite rule in WordPress something like this:

    function sitemap_rewrite($wp_rewrite) {
        $rules = array('sitemap' => 'index.php?action=sitemap');
        $wp_rewrite->rules = $rules + $wp_rewrite->rules;
        return $wp_rewrite;
    }
    add_action('generate_rewrite_rules', 'sitemap_rewrite');
    
    function flush_rewrite_rules() {
        global $wp_rewrite;
        $wp_rewrite->flush_rules();
    }
    add_filter('init', 'flush_rewrite_rules');
    

    You should only need to run these functions once (when your theme is installed for example) because the rewrite rules are stored in the database.

    However, you’ll probably find that using this method you cannot access your action variable using $_REQUEST['action']. To access your variable you’ll have add it to WordPress’ query_vars array, something like this:

    function add_action_query_var($vars) {
        array_push($vars, 'action');
        return $vars;
    }
    add_filter('query_vars', 'add_action_query_var');
    

    You can then retrieve the action variable using get_query_var('action').

  2. if (strpos($_SERVER['PHP_SELF'],'sitemap')===false) {
    //sitemap not found in server string
    } else { 
    //sitemap found in server string
    }
    

    should do the trick

  3. I don’t really know WordPress so my answer will be framework/app agnostic, but you can use mod_rewrite to easily achieve this behavior (although that means either it is already enabled on your host, either you have config-edit access). Just put this in a .htaccess file at your web root:

    RewriteEngine On
    RewriteRule ^/sitemap$ /index.php?action=sitemap [QSA,L]
    

    If you already have a .htaccess file with a RewriteEngine On statement, you can safely include only the second line anywhere after your existing RewriteEngine declaration.

    What it does is basically tell apache to treat all request on /sitemap as requests on /index.php?action=sitemap.

  4. You can try checking the contents of the PHPs $_SERVER["QUERY_STRING"] variable. It should have your /sitemap part with a possibility of having some additional parameters as well.