问题
I have a wordpress platform and I am looking at displaying variable content on a page based on a variable in the url.
I have a 1 page website (www.vidlab.io) and i would like the section "GoPro Video Editing" to display information about GoPro video editing if the url is vidlab.io/?type=GoPro or information about wedding editing if the Url is vidlab.io/?type=wedding, and so on. I have read that you can use a get call, but not really sure how to have that information in the URL without getting a 404.
Any ideas on plugins to use? Or PHP that I can insert into the page to get this result?
回答1:
That is easy.
You have to use two Wordpress functions.
add_rewrite_rule()
and
add_rewrite_tag()
First you include the add_rewrite_tag()
function into your functions.php
of your theme.
For Example:
function custom_rewrite_tag() {
add_rewrite_tag('%food%', '([^&]+)');
add_rewrite_tag('%variety%', '([^&]+)');
}
add_action('init', 'custom_rewrite_tag', 10, 0);
After that you have to choice one page of wordpress which contains your content. You have to use the page ID of this page.
Than you include the add_rewrite_rule()
in your functions.php
.
For Example:
function custom_rewrite_rule() {
add_rewrite_rule('^nutrition/([^/]*)/([^/]*)/?','index.php?page_id=12&food=$matches[1]&variety=$matches[2]','top');
}
add_action('init', 'custom_rewrite_rule', 10, 0);
Notice!:
After this you have to go to your settings -> permalinks
and only push the save button to clean your permalink cache.
IMPORTANT: Do not forget to flush and regenerate the rewrite rules database after modifying rules. From WordPress Administration Screens, Select Settings -> Permalinks and just click Save Changes without any changes.
My example is from the codex page of wordpress:
https://codex.wordpress.org/Rewrite_API/add_rewrite_rule
https://codex.wordpress.org/Rewrite_API/add_rewrite_tag
来源:https://stackoverflow.com/questions/33515393/wordpress-display-variable-content-based-on-variable-in-url