Multi Param URL redirect issue in wordpress - wordpress

I have a bit of an issue I cannot seem to get around.
On a WordPress install we have these special profile pages that were triggered by a URL structure such as this
/our-firm/profile/1/Some.Name
They wanted the name appended to the URL so the URL's were prettier. This looks like it was previously managed through some type of plugin before we got it. Now a recent WordPress update has corrupted that plugin, and this functionality no longer works. I have it where it at least works if you do not use the name, example:
/our-firm/profile/1/
But that of course is not what the client wants. I have attempted to remedy the issue with some .htaccess rewriting that follows:
RewriteRule ^our-firm/profile/([0-9]+)/([^+]+)?$ our-firm/profile?id=$1&name=$2 [L,QSA]
But I am not getting anywhere with it. What weirder is, and it may just be something I am over looking, but if I visit:
/our-firm/profile?id=1&profile_name=Some.Name
That even works fine.
Any help would be great on this. Thanks in advance!!

You can use add_rewrite_rule of WP (http://codex.wordpress.org/Rewrite_API/add_rewrite_rule)
Example:
function wptuts_add_rewrite_rules() {
add_rewrite_rule('^path-1/([^/]*)?$','index.php?page_id=PAGE_ID&nameSurname=$matches[1]','top');
flush_rewrite_rules();
}
add_action( 'init', 'wptuts_add_rewrite_rules' );
function add_query_vars($aVars) {
$aVars[] = "nameSurname";
return $aVars;
}
add_filter('query_vars', 'add_query_vars');
and You get the params in the page using $wp_query->query_vars["nameSurname"];

Related

add_rewrite_rule not working when referencing child page name as matches

Is anyone able to comment why this does not work.
I have created a custom post type called "knowledge-hub". I also then created a page called "knowledge-hub" to act as the landing page for my CPT listings, which I show using code. On one of the CPT pages, "minimum-wage-policies", I want to be able to access a variable in the URL, e.g. ?some_var=xyz. But I want it friendly like /knowledge-hub/minimum-wage-policies/xyz.
So I have created rewrite URLs. The page name "minimum-wage-policies" will vary for many of the CPT pages, so I cant hard code this. I want to access it using a URL part.
But I cant get the add_rewrite_rule() to match matches[1] to the page name. If I hard code this page name in the add_rewrite_rule it works! But as soon as I replace it with matches[1] it does not work, its either a 404 or a redirect back to minimum-wage-policies with no variable on the end.
URL would be:
http://my-domain.com/knowledge-hub/minimum-wage-policies/some_var
Referencing the child page name works:
add_rewrite_rule(
'knowledge-hub/([^/]*)?/([^/]*)/?$',
'index.php?post_type=knowledge-hub&pagename=minimum-wage-policies&my_var=$matches[2]',
'top'
);
matches[2] is working in this case as I can see the value passed in the URL in my code.
But using matches[1] does not work and returns a 404:
add_rewrite_rule(
'knowledge-hub/([^/]*)?/([^/]*)/?$',
'index.php?post_type=knowledge-hub&pagename=$matches[1]&my_var=$matches[2]',
'top'
);
Visiting the WP URL http://my-domain.com/index.php?post_type=knowledge-hub&pagename=minimum-wage-policies&my_var=xyz works, so that structure is OK.
I have tried various regex expressions used by various others on the internet, so not just ([^/])?. So am not sure if it is to do with the regex and I just have not found the right one. I want to match anything. Same issue with (.)
I also have this:
function add_my_vars($vars)
{
$vars[] = 'my_var';
return $vars;
}
add_filter('query_vars', 'add_my_vars');
Update:
Using $request->matched_query I could see the URLs being called.
When I use pagename=minimum-wage-policies the URL is as expected:
post_type=knowledge-hub&pagename=minimum-wage-policies&my_var=xyz
When I use matches[1] is completely changed which is quite bizarre:
knowledge-hub=minimum-wage-policies%2Fxyz&page=
I managed to get it working with this rewrite_rule but I have not found this structure online so not sure if its technically correct but it works. Note the use of knowledge-hub=$matches[1]. This was discovered from viewing the $request->matched_query I mentioned was bizarre above. Replicating it in the rewrite_rule makes it work.
add_rewrite_rule(
'knowledge-hub/([^/]*)?/([^/]*)/?$',
'index.php?knowledge-hub=$matches[1]&my_var=$matches[2]',
'top'
);

Home page url rewriting Wordpress

I want to do a URL rewrite in the WordPress home page
I want to change my URL http://mysite.loc/?pays=senegal to look like http://mysite.loc/senegal.
The problem is that I am on the WordPress home page, so it will be confused with the URL of another page like http://transfert.loc/page-example.
I have already tried several optins but am completely blocked.
Here is my code example:
public function rewrite_urls(){
add_rewrite_tag( '%pays%','([^&]+)' );
add_rewrite_rule(
'([^/]+)',
'index.php?pays=$matches[1]',
'top'
);
}
Can someone help me please!
Thanks
Two problems I see- rewrite rules need to set query vars that will result in a successful main query. Setting just a custom var like slide doesn't parse to anything WordPress can load. Additionally, slide needs to be added to the recognized query vars for it to get parsed within a rule.
So, what would a rule look like that would load the front page posts in the main query? That's a good question- the posts page is a special case, the absence of any other query vars. I haven't found a way to do that with a rule, though it may exist.
An easier way to do this is with a rewrite endpoint:
function wpd_endpoint(){
add_rewrite_endpoint( 'page-example', EP_ROOT );
}
add_action( 'init', 'wpd_endpoint' );
Keep in mind that if you have code accessing values via $_GET, this still won't work, because WordPress doesn't put query vars there when rules are parsed. You can change the code to use get_query_var, or just assign it before the code tries to access it:
$_GET['page-example'] = get_query_var('page-example');

Can I edit my .htaccess to write some WorldPress URL's (custom rewrites)?

So here's the problem: We don't like the fact that WordPress doesn't allow duplicate slugs, even for sub categories meaning we cannot have urls like:
product-1/guides
product-1/articles
product-2/guides
product-2/articles
That's very annoying! One solution we are considering is setting up our slugs like this:
product-1/product-1-guides
product-1/product-1-articles
product-2/product-2-guides
product-2/product-2-articles
But in our htaccess - can we use it to pick up such urls and rewrite them as prettier urls which have the product name removed from the sub folder? We don't mind hard coding these as we'll only ever have 5-10 products on the site.
This would keep the WordPress install happy with unique slugs, but the SEO tick in the box with better looking urls.
I just need a hand with the syntax please?
EDIT 1:
After looking at the WordPress Rewrite API, I'm failing to get anywhere with what I think is a really simple test. I have the following code in my functions.php which is running as I tested an echo, but no rewriting is taking place?
add_action( 'init', 'productRewrites' );
function productRewrites() {
add_rewrite_rule('^wordpress/james?','index.php?author_name=jwilson','top');
}
Nothing happens when I hit:
mysite.com/wordpress/james
Edit 2:
Cool I realise I now have to click save each time. The problem I now have is the following does not work not when I use $matches[1] - it only works if I hard code the author_name value (to jwilson for example):
function productRewrites() {
add_rewrite_rule(
"writer/([^/]+)/?",
"index.php?author_name=$matches[1]",
"top");
}
When I use $matches[1] it just returns everything! So clearly isn't using ([^/]+) in the url?!
you have to reset permalink structure
in order to do that, move to Settings -> Permalinks and press Save changes button

Wordpress custorm URL variables causes strange redirect

I'm trying to have custom variables in my URL for Wordpress site. I have read up as much as I could find on the subject and so far have the following in my functions page:
function add_query_vars($aVars) {
$aVars[] = "mrdrct";
return $aVars;
}
// hook add_query_vars function into query_vars
add_filter('query_vars', 'add_query_vars');
And the following on my header page:
if(isset($wp_query->query_vars['mrdrct'])) {
$mVar = $wp_query->query_vars['mrdrct'];
echo "variable is $mVar <br />";
}
Just to test out if things are being passed correctly and they are. However, when I use a link with the url variable in it - say www.mydomain.com/?mrdrct=myVarable - I am not directed to my homepage of my Wordpress site which is set to a static page with a template on it - I am instead directed to a page with my latest posts on it. I cannot figure out why this is happening - any ideas? Hopefully I've explained this well enough.
Thanks.
When WP sees a query string (? after the URL) it will attempt to display matching posts using it's rewrite rules. If no posts match it will show a 404 error - I would guess you do not have a 404.php file, so WP is showing the default which is index.php (see the Wordpress Template Hierarchy for more details on that).
I'm not 100% sure what you want to achieve, but I'd suggest that you need to look at changing the query when $wp_query->query_vars['mrdrct'] is set. See the WP Codex for query_posts() for a good place to start, if you are not already familier with it.

WordPress rewrite URL to access plugin page

Hi i am trying to access my plugin via a custome URL but i am unable to get the plugin to redirect, it just comes up 404 page not found, whereas what i want is page.php to be called instead. My plugin code is below (activate and deactivate functions of the plugin):
register_activation_hook(__FILE__,'activate');
register_deactivation_hook(__FILE__,'deactivate');
function setRewriteRules()
{
add_rewrite_rule( 'plugin-url/$', '/wp-content/plugins/my-plugin/page.php', 'top' );
}
function activate()
{
setRewriteRules();
global $wp_rewrite;
$wp_rewrite->flush_rules(true);
}
function deactivate()
{
global $wp_rewrite;
$wp_rewrite->flush_rules(true);
}
Any ideas what i am doing wrong?
Thanks in advance,
Chris
First off, giving the path that way is a bad idea, because if for any reason any of that changes, your plugin/theme breaks.
Ozh makes a great suggestion under the section Hardcoded Paths as far as those go...
Secondly, you're most likely going to be better off using *query_vars*. Have a look at http://www.rlmseo.com/blog/passing-get-query-string-parameters-in-wordpress-url/ and possibly even http://planetozh.com/blog/2011/01/pretty-login-url-a-simple-rewrite-api-plugin-example/ for examples of how to do this.
Also checkout the WP_Rewrite Class as it has the best information on handling URL rewriting in WordPress.
Thirdly, you need to hook your setRewriteRules() function to the init hook, because the first time the rules are flushed, your rules will be removed.
So your code would look something like this (without any other corrections):
register_activation_hook(__FILE__,'activate');
register_deactivation_hook(__FILE__,'deactivate');
add_action('init', 'setRewriteRules');
function setRewriteRules()
{
add_rewrite_rule( 'plugin-url/$', '/wp-content/plugins/my-plugin/page.php', 'top' );
}
function activate()
{
setRewriteRules();
global $wp_rewrite;
$wp_rewrite->flush_rules(true);
}
function deactivate()
{
global $wp_rewrite;
$wp_rewrite->flush_rules(true);
}
Rewrite Rule Flushing
Here's some tips on flushing your rewrite rules...
Rewrite Rules are flushed automatically anytime you visit Settings > Permalink or anytime you make and save changes them in the Admin area.
Adding add_action('admin_init', 'deactivate'); might also be helpful so they are flushed anytime an Admin page is loaded.
Rewrite rules that don't redirect to the Wordpress index.php file are written to the .htaccess file. I don't think they are ever stored in the database. So, looking at your code, if your .htaccess file is not writable when the plugin is activated, then your rewrite rule is never added.
As Amereservant wrote you need to add your rewrite rule in an init (or perhaps generate_rewrite_rules) action, as otherwise it'll get removed anytime the rules are flushed (because as described they are not stored in the database).

Resources