Home page url rewriting Wordpress - 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');

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'
);

Wordpress Url Rewrite with Multiple Parameters and Templates - Dynamic Path/Parameter Placement

We're having some trouble figuring out WP URL rewrite rules when we have tokens separated by parameters. Very briefly, we'd like to have the following common format for user pages and video libraries:
/users/steve/videos/2
...where "users" is the PHP page template that displays details on a user. So if we go to:
/users/steve/
...we see Steve's home page. If we go to:
/users/steve/videos/
...we hit the page template for the video library, and we see Steve's list of videos. And if we go to:
/users/steve/videos/2
...we hit a third page template, the video player page, where we see video id 2 displayed.
So we have three separate page templates, and we would like the child / parent relationship between them to be user page -> video library page -> video player page, for our breadcrumbs display.
The trick we can't figure out is that "steve" and "2" are really params inserted into the url, interrupting the parent/child token relationship. And second, for the video player, there really isn't a token there at all that maps to the video player page template. It's just the presence of the "videos" token plus the additional numerical parameter that tells us this maps to the video player page template.
As alternative, we've figured out how to get /users/videos/steve/2 working. We've added this rewrite rule to our child theme's functions.php file:
add_rewrite_rule(
'^users/videos/([^/]*)/([^/]*)/?',
'index.php?pagename=users/videos&users_filter_name=$matches[1]&user_video_id=$matches[2]',
'top');
(we've also defined the variables "users_filter_name" and "user_video_id" and we are successfully parsing them in the template)
But since what we really would like is /users/steve/videos/2 we tried updating the rule to:
add_rewrite_rule(
'^users/([^/]*)/videos/([^/]*)/?',
'index.php?pagename=users/videos&users_filter_name=$matches[1]&user_video_id=$matches[2]',
'top');
That didn't seem to work (it just loaded the '/users/' page) so we're obviously doing it incorrectly. Is what we want achievable with this structure?
Thanks!
The link structure of /users/steve/videos/2/ format is not a problem for Wordpress, and you actually wrote all the right code, but there is a small mistake somewhere.
Most likely you have a problem in the code section where you add new variables to query_vars.
Perhaps you are adding a second variable in too late action.
When Wordpress sees an obscure variable, it often behaves as you described.
Try removing all of your code and copy this to functions.php top
add_rewrite_rule(
'^users/([^/]*)/videos/([^/]*)/?',
'index.php?pagename=users/videos&users_filter_name=$matches[1]&user_video_id=$matches[2]',
'top');
add_filter( 'query_vars', function( $vars ){
$vars[] = 'users_filter_name';
$vars[] = 'user_video_id';
return $vars;
} );
If it doesn't work, try changing the code to this
add_rewrite_rule(
'^users/([^/]*)/videos/([^/]*)/?',
'index.php?page_id=54&users_filter_name=$matches[1]&user_video_id=$matches[2]',
'top');
add_filter( 'query_vars', function( $vars ){
$vars[] = 'users_filter_name';
$vars[] = 'user_video_id';
return $vars;
} );
Where 54 = your page ID
After each change you must go to the settings and turn off/on permalinks to reset the cache
I tested this code on my demo it works 100%.

Wordpress add rewrite rule doesn't work for me

I'm developing a plugin that creates 2 pages: one listing page and one details page.
I don't use custom types. I have created a table into the database where I save the company details and also a slug for the details page.
It's working properly but I have a problem with the URLs. They are not pretty.
On the listing page I use this code to create the link:
<?php echo stripslashes($value->company_name); ?>
The generated link looks like this:
https://www.website.com/company/details/?companyname=new-company-name
I use the query because I need it on the details page, where I use this code:
$company_slug = $_GET['companyname'];
$company_details = $wpdb->get_row("SELECT * FROM $table_company WHERE company_slug = '$company_slug'");
This is how I retrieve the company details from sql and it also works just fine.
I have created manually in Wordpress the details page.
The problem is that I want the details URL to look pretty, like this:
https://www.website.com/company/details/new-company-name/
Generating it like this it's easy but when I click, I get a 404, since the query from URL is missing.
I was thinking it's easy to create directly the pretty URL and on the details page to parse the URL and get the company slug. It didn't work. I get a 404 maybe because the page doesn't physically exist.
So, I've done some research about URL rewrite and I have found some examples but none worked.
I have found tried this code also:
add_filter('query_vars', function($vars) {
$vars[] = "companyname";
return $vars;
});
function custom_rewrite_rule() {
add_rewrite_rule('^companyname/?([^/]*)/?','company/details/?companyname=$matches[1]','top');
}
add_action('init', 'custom_rewrite_rule', 10, 0);
I've read that I shouldn't use matches if I use a custom URL instead of index.php, so I have also tried without matches:
add_rewrite_rule('^companyname/?([^/]*)/?','company/details/?companyname=$1','top');
No results. If course, after every change I have saved again the permalinks.
This should be an easy task but somehow it doesn't work.
https://developer.wordpress.org/reference/functions/add_rewrite_rule/
Does anyone of you know how can I make this work?
Thank you.
Regards,
AG
I am assuming that the details page you created has the slug company/details. Here's what you need to do to make it work-
1. Add the custom rewrite rules in functions.php file:
function theme_custom_rewrites() {
add_rewrite_tag("%companyname%", "([a-z0-9\-_]+)");
add_rewrite_rule('^company/details/([a-z0-9\-_]+)/?$', 'index.php?pagename=company/details&companyname=$matches[1]', 'top');
}
add_action('init', 'theme_custom_rewrites');
It registers a new rewrite tag/query var named companyname to be used later and registers a custom rewrite rule for the specific URL structure you want (/company/details/company_name).
2. Get the company name on the template file and use it: After you have added the above code and saved the permalinks, you can get the companyname just by using the get_query_var() function.
$companyname = get_query_var( 'companyname' );
Hope it helps. Thanks.
Thank you very much for your fast reply. It worked.
Of course, I had to change the link on the listing page to:
<?php echo stripslashes($value->company_name); ?>
I have removed the query from the link and it looks like this now:
https://www.website.com/company/details/new-company-name/
What I don't understand, is how does WP know which is the query, since I removed it from the link.
I can see the same data if I access
https://www.website.com/company/details/?companyname=new-company-name
or
https://www.website.com/company/details/new-company-name/
But, basically, this part (?companyname=) doesn't exist anymore in the link, since I changed it.
I have no query now in my plugin, but somehow everything works properly. :)
I did not declare it somewhere. It's completely gone and it works.
How does this code know that the query exists and it's retrieving the slug from the database?
$companyname = get_query_var( 'companyname' );
I only have this code now:
<?php echo stripslashes($value->company_name); ?>
So, no query in URL.
Thank you for your time.
Regards,
AG

Wordpress re write rule

Lets say I have a URI thats portfolio_categories/guttersspouting/
How could I rewrite a function to change it too "products"
ok as requested this matches the uri "product" exactly. This is not advisable if releasing code to a third party, as if they create a page called product, it will follow this rule.
Btw I am assuming you mean post_type = page (will also work for posts, see the post_id= in the add_rewrite_rule? You need to change this to the post id of the page you want to redirect to.
add_action('init', 'new_rewrite_rule');
function new_rewrite_rule(){
// matches product exactly, product/aproduct will fail, etc
// you need to add your own post_id into the function below.
add_rewrite_rule('^product$','index.php?page_id=12','top');
}
You will need to flush the rewrite rules for this to work (go to the permalinks setting page and just hit the save button)
code version of flush rewrite rules, not a good idea to have it running on wp_loaded, should be on a activation hook really but for testing this will do:
function new_flush_rewrite_rules() {
flush_rewrite_rules();
}
add_action( 'wp_loaded', 'new_flush_rewrite_rules' );
Just to note you can also do this manually in the post edit screen.

wordpress auto generate pages from sub url of page

Hoping someone can help. I don't want to create actual pages in the backend of wordpress but i want to know how i can make it so if anyone goes to a url: mydomain.com/page/sub-url.
Then i can grab that "sub-url" and output a page with content i generate via php.
If i grab that "sub-url" and i don't want to output i can do a 404 error.
I want to try to stay away from editing the htaccess file is possible but if i need to i can.
Everytime i try search for this, i get result for creating actual pages in the backend automatically which i don't want.
I think what you're looking for is a custom rewrite endpoint, which you call 'page'. Then on yourdomain.com/page/sub-url, 'page' is the parameter and 'sub-url' is the value. You can get that value with the function get_query_var().
After applying, be sure to go to your Wordpress admin->Settings->Permalinks, and click save to flush the current rewrite rules.
Update:
Use this code to show a 404 page
global $wp_query;
$wp_query->set_404();
status_header( 404 );
get_template_part( 404 );
exit();
(source)

Resources