1

I am having trouble with passing variables in my wordpress url. When i pass the variable and the value to the url, all is well i.e.

mysite.com/product-part/?part=1/

but what i want is for the variable to be passed as follows:

mysite.com/product-part/1

In php, the normal way to pass variables to a url is:

mysite.com/?id=1

In wordpress, the above would look like this:

mysite.com/1

How can I achieve the above?

2 Answers 2

1

The Rewrite API lets you add create custom rewrite rules inside WordPress. You can call add_rewrite_rule() inside the "init" hook and give it a regular expression to translate into a query string. Something like:

function setup_rewrite_rules() {
    add_rewrite_rule('^store/([0-9A-Za-z]+)/([0-9]+)/?', 'index.php?product_slug=$matches[1]&part=$matches[2]', 'top');
}

add_action('init', 'setup_rewrite_rules');

Note that the URL isn't an exact match for the existing product URLs because you need something that matches this regular expression.

You'll probably need to use a template_redirect handler to detect when these variables are set and show the normal product page since you're not using the product's normal permalink.

Sign up to request clarification or add additional context in comments.

Comments

0

This is a very, very bad way to pass a variable. Wordpress uses "re-write" rules to determine what query to run. These "permalinks" identify, for instance, what post your are going to. In your example, using an integer such as "1", you could pass a variable by writing a re-write rule that said something like "all integers are a variable", or "all slugs that start with an integer are a variable" but you would soon get into conflicts with post names. What about posts that start with numbers, for instance? Also, many plugins would use permalinks to send you to certain pages, and you could come into conflict there. Better to use any of these things to pass variables:

get variables
post variables
hidden post variables
session variables
nonces
Wordpress meta-data like user meta data

Good luck

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.