Wordpress URL rewrite not working/registering - wordpress

I've been trying to get my head around Wordpress URL rewrites, but I'm having no luck.
What I want to do:
I building a custom plugin where a user can build products from various options. The options collectively build a code which refers to the unique product the customer has built.
The code might be something like 140-3-WPA-ABC-2.
The plugin will appear on a single dedicated page:
http://wordpress-site/configurator/
I want a customer with a prexisiting code to be able to enter it into the url like this:
http://wordpress-site/configurator/140-3-WPA-ABC-2/
Whereupon, the plugin gets the variable, and uses it to build the correct product.
Problem
It should be fairly simply but I can't get anything to work using the Wordpress URL rewriting rules, I can't even get anything to seemingly get registered as a Wordpress query var.
I've been trying the following in the main plugin initialisation code:
add_filter( 'query_vars', 'conf_query_vars' );
add_action( 'init', 'cong_rewrites' );
function conf_query_vars($query_vars){
$query_vars[] = 'product_code';
return $query_vars;
}
function conf_rewrites(){
add_rewrite_rule(
'configurator/([^/]+)/?$',
'index.php?product_code=$matches[1]',
'top'
);
}
If I then try and open http://wordpress-site/configurator/140-3-WPA-ABC-2/ I get a page not found error. Echoing query_vars seems to show the variable 'product_code' is not created.
ps I've tried flushing the rewrite cache. Apologies for cross-posting to Wordpress.stackexchange.com - but seems programming question better here?

Try this, I had the same problem.
add_action('init', function() {
add_rewrite_endpoint('sponsor', EP_ALL);
});
add_filter('request', function($args) {
print_r($args);
return $args;
});
I think you should just integrate the function add_rewrite_endpoint.

Related

Woocommerce display downloadable files with an external url

I need help with this: I need that the url of the downloadable products link with an external url. I´m trying to add a custom field and replace the filters woocommerce_product_file and woocommerce_product_file_download_path but it didn't worked, I think because I can´t call to the product data from the order. Someone did this? Thank you for your help!
The code doesn't works. Now is something like:
*function mostrar_campo_personalizado_en_order($file_id){
global $wpdb, $woocommerce;
echo get_post_meta($file_id, 'downloadable_url', true);
}
add_filter( 'woocommerce_product_file', 'mostrar_campo_personalizado_en_order', 10, 1 );
add_filter( 'woocommerce_product_file_download_path', 'mostrar_campo_personalizado_en_order', 10, 1 );*
I don´t know if I´m working in the correct way, I need to change the url of the downloadable products because woocommerce internally routed. Because I couldn't modify him, I intente removal and display a custom post field. The page is in a test server because the site is on line. The url of the tester server ishttp://lab.jus.raffles.com.ar/my-account/ but you need credential to come in:
user: paula
pass: 5VPeGgAHWzYX1T

How bad is $wp_rewrite->flush_rules() on 'init' action hook?

According to the Codex:
[...] This function can be extremely costly in terms of performance. It should be used as sparingly as possible - such as during activation or deactivation of plugins or themes. Every attempt should be made to avoid using it in hooks that execute on each page load, such as init.
Ok, so, I know it shouldn't be used in every page load and I'm not, but I still need a very conditional rewrite rule on this project.
I have these 2 url structures:
- example.com/products/tables/fancy-computer-table //This is a product url, here I expect the normal behavior from wp.
- example.com/products/tables/office //This should be some kind of a filter, where the site gets all the tables related to the office department. Note how both URL structure matches.
To make it work, I narrowed it down to these very specific URLs, using some regex. If matched, I'll run 2 queries to verify if the url I'm in is for the filter I want that rule to apply, or if it's a product url. In the latter, I want wordpress to behave normally. But I have to flush the rules either way, whether it's a product or it's the category and the filter, so that both pages work properly and dinamically.
I do all this to narrow down the use of this function to the least possible, but the Codex doesn't really tell me how bad it does affect the performance, or why.
I'm passing the parameter on that function as false by the way, so it doesn't rewrite my htaccess file, but I'm not sure where that rewrite rule option is stored, if it's on the memory somewhere, or on the database, wish they would provide some clarification on that.
Thanks in advance for reading this question. Any pointers are appreciated here, even if you want to point me to some other way of doing this. :)
EDIT: Posting some code here so you guys can actually understand what I mean and let me know if this maybe this could be bad practice... maybe a suggestion on how to do it better.
<?php function custom_rewrite_products()
{
// regex to match either "products/tables/fancy-computer-table" or "products/tables/office"
preg_match('#products\/([^\/]+)\/([^\/]+)\/?#', $_SERVER['REQUEST_URI'], $url_matches);
if(is_array($url_matches)) {
$query_category = new WP_Query('category_name='.$url_matches[1]);
$query_category->get_posts();
$args = array(
'post_type' => 'filters',
'name' => $url_matches[2]
);
$query_post = new WP_Query($args);
$query_post->get_posts();
if($query_category->have_posts() && $query_post->have_posts()) {
$category_ID = '';
$filter = '';
$category_ID = '' . $query_category->query_vars['cat'] . '';
$filter = '' . $query_post->query_vars['name'] . '';
$string = "index.php?cat={$category_ID}&filter={$filter}";
add_rewrite_rule('products/([^/]+)/([^/]+)/?$', $string, 'top');
}
global $wp_rewrite;
//Call flush_rules() as a method of the $wp_rewrite object
$wp_rewrite->flush_rules(false);
}
}
add_action('init', 'custom_rewrite_products');
I still don't understand why, but the flush is needed here, so the $category_ID and $filter variables actually get passed to the rewrite rules. If I take it out, the rewrite just goes to the index page, the place where the values should be are empty.
In case you're wondering, I created the filters on a custom post type and they are related to each post by using a custom field, since they're like four or five and they're present on every category on this project. As you can see, I already have a category/subcategory structure and I didn't find it smart to create these filters once again by hand inside each main category.
There is a 'rewrite_rules' record in the 'wp_options' table that includes all the rewrite rules. When calling flush_rules(), WordPress will clear this record and regenerate all the new rules, including the ones you're not changing.

How to achieve SEO friendly urls with Wordpress and custom parameters

I am having a big problem where I cannot use the Linkedin Share button.
One of the reasons is the non friendly URLs I am using.
Basically I have built a plugin for wordpress which shows me jobs.
It is working perfect show the jobs and everything but the link looks like this
www.recruitmentagency.com/job/?id=250
and I want it to look like
www.recruitmentagency.com/job/250
or
www.recruitmentagency.com/job/job-id/250
I tried to add rewrite rules to htaccess with no luck
RewriteRule ^job/([0-9]+)/$ job/?id=$1
RewriteRule ^job-id/([0-9]+)/$ /?id=$1
and none of them worked.
Any solution will be greatly appreciated.
I tried to use the inbuilt system and it is partially working.
However I don't like the way it is doing it so.
Instead of getting the job like
$job_id=$_GET['id'];
I am getting it like
$job_id=wp_query->query_vars['page'];
when the page is load like
www.recruitmentagency.com/job/250
I can't even understand why my supposed job-id is appearing as a page, but I am using it since I need this to work.
I was also facing the same issue. after long time I have reached the below solutions:
add_filter('rewrite_rules_array','job_rewrite_rules_array');
function job_rewrite_rules_array($rules){
$job_page = get_post(123);
$job_rules = array();
if( is_object($job_page) ){
$job_slug = $job_page->post_name;
$job_rules[$job_slug.'/([^/]*)$'] = 'index.php?pagename='.$job_slug.'&jobid=$matches[1]';
}
return $job_rules + $rules;
}
//Bind Query Var
add_filter('query_vars','job_query_vars');
function job_query_vars($vars){
array_push($vars, 'jobid');
return $vars;
}
Execute job_rewrite_flush just one time
function job_rewrite_flush(){
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
add_action('init','job_rewrite_flush');
Now access the param as: $jobid= get_query_var( 'jobid', 1 )
I think the above script work as per your requirement.

add_action not working in wordpress

I am setting a WP that it should redirect all the request made to sub-directory to file inside that directory.
For example if there a visit on example.com/link/me then it should send the user to /link/index.php?me
To achieve this, I am trying to add rewrite rule in theme function file.
Here's what my code looks like:
function moin_add_rewrite_rules() {
add_rewrite_rule(
'^([^/]*)/(link)/(?:[a-z][a-z0-9_]*)?$',
'/link/index.php?$matches[1]',
'top'
);
}
add_action( 'init', 'moin_add_rewrite_rules' );
It is not working, visiting example.com/link/meshows a 404 (as link is outside WP).
Is there any problem with regex code? or anywhere else? What could be other possible solution?
Looking at the example in the Codex, the matched expression doesn't have the leading /.
Stripping the leading bit out of your regex, then, I think this should work (sorry, I don't have a test environment handy):
add_rewrite_rule('^link/([a-z][a-z0-9_]*)/?$','/link/index.php?$matches[1]','top');
Alternatively, you could do something similar in your .htaccess file.
As a side note, I think as it's currently coded, you should be using $matches[3] not $matches[1], as the value you're interested in is the third parameter in parentheses (the Codex notes "capture group data starts at 1, not 0").

Wordpress add_rewrite_rule With 3 Variables

I am having trouble getting Wordpress to assign the proper values to variables using the add_rewrite_rule() function. My goal is to have a url that looks like this: www.mywebsite.com/catalog/category1/category2/item-slug.
Here is my code from the functions.php file:
add_filter( 'query_vars', 'query_vars_new' );
function query_vars_new($query_vars){
$query_vars[]='category1';
$query_vars[]='category2';
$query_vars[]='catalog_item';
return $query_vars;
}
add_action( 'init', 'rewrite_init' );
function rewrite_init(){
add_rewrite_rule('catalog(/([^/]+))?(/([^/]+))?/?','index.php?page_id=94&category1=$matches[1]&category2=$matches[2]&catalog_item=$matches[3]','top');
}
So the goal is to have three variables $category1, $category2, and $catalog_item with the values from the corresponding url segments. However, when I test this the first two variables are set to the same value.
For example, www.mywebsite.com/catalog/clothes/shirts/polo-shirt should return:
$category1="clothes";
$category2="shirts";
$catalog_item="polo-shirt";
But instead I get:
$category1="/clothes";
$category2="clothes";
$catalog_item="/polo-shirt";
There must be something wrong with my add_rewrite_rule function, but I can't figure it out.
Thanks to the incredibly underwhelming response to this question I ended up just making it work without the help of the Wordpress variables. I just configured Wordpress to allow the variables in the url, then used PHP to fetch the URL and get the different URL segments and analyze them. Not quite as pretty as the Wordpress method, but at least it works.

Resources