Wordpress re write rule - wordpress

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.

Related

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

How to POST to admin-post.php from Avada formbuilder form

Using the Avada theme's form builder functionality, I’m attempting to use the “Send to URL” option to POST the form and then run an api call in a plugin I’ve written.
I was thinking I could set the “Send to URL” value to /wp-admin/admin-post.php and add a hidden field to the form named “action” with a value of “make_api_call” to get it to run the code in my plugin set up like so:
add_action('admin_post_make_api_call', 'make_api_call');
function make_api_call()
{
//todo: make the api call
wp_redirect(‘another-page’);
}
However, this does not work and returns this from the server: {"status":"error","info":"url_failed"}
What I want to do is to POST the form to admin-post.php, have my plugin run code when it POSTs, and then redirect to another page.
I've checked the documentation for the AVADA theme and it only says that you can specify a url to post to but doesn't give any additional details.
So I eventually got something to work, and I'm not knowledgeable or experienced enough with WordPress development to know if it is the "right" way, but it works well.
I realized that using the "Send to Url" option on the Avada form, it was POSTing the form to the admin-ajax.php file. There's plenty of documentation on that and I was able to partially make that work but I was not able to make it fit my use case b/c even though there is a way to configure the Avada form to redirect to a different URL on success I couldn't append parameters to that URL based on the return value from admin-ajax.php.
For future reference, here's what I was able to make work but not fit my use case by having the Avada form submission set to Send to Url. (I'm recreating this and some of it's from memory since I went with a different solution, so it may not be 100% runnable.)
The way admin-ajax works is all requests to admin-ajax.php are eventually handled by a WordPress action (filter?) like so:
add_action( 'wp_ajax_my_action', 'my_function' );
In the above, my_action is what you've set as the form's action by creating a hidden input element on your html form named action and setting it's value to "my_action". The my_function argument is the name of the function you want to run when the action happens.
add_action( 'wp_ajax_my_action', 'my_function' );
function my_function(){
//do stuff
}
Watching the request in Chrome's dev tools, I could see the action the form was setting was fusion_form_submit_form_to_url.
So ended up with this:
add_action( 'wp_ajax_fusion_form_submit_form_to_url', 'my_function' );
function my_function(){
//do stuff
}
You can see that the url you enter in the Form Submission URL field gets passed to admin-ajax as fusionAction. Whether the Avada theme does something additional with that - I don't know but you could use it to control the logic that gets executed in my_function. I suspect there's an action in the Avada form that works similar to the wp_ajax_ WordPress action but by the time I got this far I realized this wasn't going to work so I pivoted to the actual solution, below.
All of that worked okay but you can't redirect out of a call to admin-ajax.php unless you do it on the client side and I didn't want to dive into that.
What I was able to make work was configuring the Avada form to do a traditional HTTP POST. I added a hidden input element on the Avada form with a name of formName and the value set to the name of the form I wanted to handle.
In my plugin code, I hooked into the WordPress init action as in the code sample below, and then customized the logic to be executed based on which formName was sent in.
add_action('init', 'callback_function');
function callback_function()
{
if (isset($_POST['formName'])) {
$form = $_POST['formName']; //from the hidden input element "formName"
//there is a call to wp_redirect in each case
switch ($form) {
case 'form1':
process_form_1();
break;
case 'form2':
process_form_1();
break;
default:
# code...
break;
}
//without this "exit" you will get errors similar to "headers already sent"
exit;
}
}
This allowed me to run the code I needed to run based on what form was submitted, and redirect to the correct place afterward.

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 automatically created a redirect that I need removed

I made an edit to a page on a Wordpress site that included changing its parent. Unfortunately I was not paying attention and this move somehow changed the permalink/slug which I saved before noticing. In addition Wordpress automatically created a 301 redirect to go from the original URL to this new URL. I went back in and changed the permalink/slug back to the original but that redirect still stands so it stills sends the page to the new url it created rather than keeping it to updated option (updated meaning me typing in the original slug).
I am looking for a way to remove the 301 redirect, but do not know where to start.
The original URL: https://www.synergex.com/rev11
The newly generated URL: https://www.synergex.com/products/synergy-de-rev11-licensing-faq
I also tried simply creating a brand new page using the original slug/permalink /rev11 but it gets changed to /rev11-2 so it seems like it it must remember the /rev11 somewhere.
I am hoping there is a way to do this through the WP Dashboard and am open to suggestions. This site does have the Redirection plugin installed but I've checked through the lists and this redirect was not created or listed in it. I also tried to add a redirect to do the opposite (redirect from the new URL to old) but of course it just created a loop that timed out.
EDIT 1.2: You probably have a problem with your old permalinks not getting flushed properly. But do not worry the great people at Wordpress got a function for that called flush_rewrite_rules();
Remove rewrite rules and then recreate rewrite rules. This function is
useful when used with custom post types as it allows for automatic
flushing of the WordPress rewrite rules (usually needs to be done
manually for new custom post types). However, this is an expensive
operation so it should only be used when necessary.
Source # https://developer.wordpress.org/reference/functions/flush_rewrite_rules/
Add the following to the top of your function.php:
<?php
/**
* Removes a function from a specified filter hook.
* More about flush_rewrite_rules(); # https://developer.wordpress.org/reference/functions/flush_rewrite_rules/
*/
flush_rewrite_rules();
/*
* Remove rewrite rules and then recreate rewrite rules.
* More about remove_filter(); # https://developer.wordpress.org/reference/functions/remove_filter/
*/
remove_filter( 'template_redirect', 'redirect_canonical' ); ?>

How to update update existing custom post type with register_post_type permanently?

I want to perform quick rewrite slug update for my custom post type on the fly. So I use code like in my theme's functions.php:
$no = get_post_type_object($pt_slug);
$no -> rewrite['with_front'] = false;
$no -> rewrite['slug'] = $slug;
register_post_type($pt_slug, $no );
Which is hooked to 'init' add_action('init', 'check_post_type_rewrite_url');
There is large code so I write only issue part in here.
register_post_type returns object with updated slug. I understand it means my custom post type was updated, but it was not. Existing post type still has its old rewrite slug. Should I add something special for rewrite rules to save changes and make it work? Or there is specific way to register/update post types with rewrite slug so it worked?
The way you solved the issue - by using flush_rewrite_rules - is technically correct but not recommended. As stated in the doc:
This function is useful when used with custom post types as it allows for automatic flushing of the WordPress rewrite rules (usually needs to be done manually for new custom post types). However, this is an expensive operation so it should only be used when absolutely necessary.
So you shouldn't keep your flush_rewrite_rules() call in your init hook, as it will regenerate all the rewrite rules at every page load, which is really badly ressource consuming.
Usually it's enough to just visit the Permalinks Settings page to flush the rules - so if you change again your CPT slug in the future, just visit the page once.
If your slug could change dynamically, then you can make use of flush_rewrite_rules(), but you need to use it carefully - it shouldn't be called on every page load, but could be used by a periodic cron job, or on plugin activation / deactivation, depends of the case.

Resources