Lars Mertens Lars Mertens - 8 days ago 5
PHP Question

Using custom wordpress url link parameter instead of GET value in url

I will keep this very short.

I've read some tutorials about changing the following url for Wordpress:


localhost/mysite/werkvorm?item=test


To:


localhost/mysite/werkvorm/test


So I can get clean links for search engines. And the page loads like its just reading the values of the
$_GET['item']
but with an easier to read url.

With the following code I tried to achieve my goal:

Functions.php:

/**
* For rewriting URLS on werkvorm
*/

add_action('init', function(){
add_rewrite_rule(
'^werkvorm/([^/]+)([/]?)(.*)',
'index.php?pagename=werkvorm&item=$matches[1]',
'top'
);
});

/**
* Retrieve the data from the get parameter for werkvorm page
*/

add_filter('query_vars', function( $vars ){
$vars[] = 'werkvorm';
$vars[] = 'item';
return $vars;
});


On the werkvorm page i can use:

$test = get_query_var( 'item' ); // to retrieve the data


Now when I use the url:
localhost/mysite/werkvorm/test

I'm getting a 404. However when I use
localhost/mysite/werkvorm/?item=test
it works fine only the url is not changed. Any help on this is appreciated.

Answer

Change the Permalink Structure to 'Post Name' in admin->settings->permalinks.

Depending on your URL structure requirements, you may have to write some code. But the post name structure setting will do the trick here.