Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress custom Querystrings & Pretty URL's - How?

I have a perfectly good (so far) setup of wordpress of for a new website. The pretty urls are working as expected.

I have 1 dynamic page that loads content depending on the querystring:

/dynamic/?loc=england&code=uk 

I wish to make this URL "pretty" as well but every-time I modify the .htaccess no changes are made. Tried everything and googled everything else - last resort. If I could get the following to work then I would be happy.

I need to make the URL look like.

/dynamic/location/england/code/uk/

Adding this to any .htaccess breaks the whole website.

RewriteRule /dynamic/(.*)/(.*)/(.*)/(.*)/$ /dynamic?$1=$2&$3=$4

What am i missing.

Thanks in advance

N

like image 760
Rough Coder Avatar asked Dec 22 '22 19:12

Rough Coder


1 Answers

Don't add the rewrite rule to your .htaccess file. WordPress manages that file for you, so try to use built-in features whenever you can.

WordPress actually has a somewhat advanced rewrite engine that ships standard - and it's pluggable just like the rest of the platform.

The trick, though, is working with it. You'll need to register your RegEx so WordPress knows what kinds of strings to match (i.e dynamic/location/(.*)/code/(.*) => /dynamic?$loc=$1&code=$2). Then you'll need to set up the page and script on the back end to handle the submission.

For a similar example, look at the answer I received to parsing custom URLs with a custom post type over on WordPress Answers. Extending this, you'll need to set up code similar to the following (note: untested!!!):

<?php
add_action('init', 'add_my_rewrite');

function add_my_rewrite() {
    global $wp_rewrite;
    $wp_rewrite->add_rule('location/([^/]+)/code/([^/]+)','index.php?loc=$matches[1]&code=$matches[2]','top');
    $wp_rewrite->flush_rules(false);  // This should really be done in a plugin activation
}

This should add the rewrite structure to your .htaccess file automatically.

like image 177
EAMann Avatar answered Dec 24 '22 09:12

EAMann