How to Rewrite the URL

Here I mentioned the url

http://localhost/wp/2016/?category_name=cricket

now i need to rearrange the url like

http://localhost/wp/cricket/2016.

here cricket is category name and 2016 is year.

Remove the ?Query String Variable not a value of the querystring in the wordpress URl.

I tried

RewriteRule ^([0-9]{4})/?$/(.+)/([^/]+)/?$ /index.php/$1/?category_name=$2[QSA,L]

But Not Working

Topic url-rewriting Wordpress

Category Web


you can have something like this for array based.

add_action('init', 'category_rewrite');

function category_rewrite() {

        global $wp_rewrite;
        $my_URL = $_SERVER['REDIRECT_URL'];
        // in my example i am testing http://localhost/news-events/2015
        // Let save the second value 
        $my_URL_PATH=explode('/',$my_URL);

        $my_CAT = Array ('news-events'=>'cricket');


        $rule = $my_URL_PATH[1].'/(\d+)/?$';
        $rewrite = 'index.php?year=$matches[1]&category_name='.$my_CAT[$my_URL_PATH[1]];
        add_rewrite_rule($rule,$rewrite,'top');
        $wp_rewrite->flush_rules();
}

Using the below code the following source url

http://localhost/cat/<catname>/<year> 

will be converted to

http://localhost/index.php?year=<year>&category_name=<catname>

Paste the code in your there functions.php

add_action('init', 'category_rewrite');

function category_rewrite() {
        global $wp_rewrite;
        $rule = 'cat/(.+?)/(\d+)/?$';
        $rewrite = 'index.php?year=$matches[2]&category_name=$matches[1]';
        add_rewrite_rule($rule,$rewrite,'top');
        $wp_rewrite->flush_rules();
}

so where I was doing mistake.

  • I was not flushing the rules
  • the rewrite should be in single quotes, including the matches , the entire thing should go as a "non compiled" string, wordpress will compile it.

WordPress will generate rewrite rules internally once you have selected a permalink format. You can do so under Settings > Permalinks in your WordPress admin area. WordPress will attempt to write to your .htaccess file. If it can't, it will provide you with some rewrite code you can copy/paste into your .htaccess file.

Either way, WordPress transforms URLs into query arguments. If you want to change the way that WordPress interprets URLs and retrieves data to be displayed, you'll need to investigate the Rewrite API.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.