Create Query String Parameter in Wordpress
Create New Query String Parameters
When you create your own rewrite rules they should all be write back to the index.php file, this is where WordPress is instantiated and the database is loaded, there are a number of querystring options you can pass through to the index.php file to get it to process the results and return the correct post. These include postname, category_name, tag, year, monthnum, day, paged.
But if you have created a new post custom meta data and want to have a custom URL to view any post with this meta information then you will need to create your own URL parameters to use on the index.php file. This is where you will need to create your own querystring parameter into the index.php file so that WordPress will understand this parameter and use it in the query variables to use in the WP_Query class.
Using the WordPress function add_rewrite_tag() we can create querystring parameters that WordPress will understand when it processes the query.
To use this function you must pass in the tagname you are going to use and the regex to check this URL matches the rule.
Know all Url rewrite tricks in Wordpress
Know all Url rewrite tricks in Wordpress
function create_new_url_querystring()
{
add_rewrite_tag($tagname, $regex, $query);
}
add_action('init', 'create_new_url_querystring');
For example if you have created a custom post meta to store the film year it was produced and you want to create a URL for these posts then you can create a rule with the following.
add_rewrite_tag('%film_year%','([^/]*)');
Now the rewrite tag is setup we can pass in a new parameter of film_year into the index.php file and pick this up in the query_vars() function.
function create_new_url_querystring()
{
add_rewrite_rule(
'^film-year/([^/]*)$',
'index.php?film_year=$matches[1]',
'top'
);
add_rewrite_tag('%film_year%','([^/]*)');
}
add_action('init', 'create_new_url_querystring');
With this now set if we need to get at this information you would use the query_vars() method.
global $wp_query;
$wp_query->query_vars['film_year'];
Or you can use the wrapper function for this which is get_query_var( $querystringParameter ).
Know all Url rewrite tricks in Wordpress
Know all Url rewrite tricks in Wordpress
$filmYear = get_query_var('film_year');
You will not be able to use the $_GET variable as the current URL will not have any querystrings as we are rewriting this page to the index.php URL.
Once we have that value we can use this to change the query and search for posts that only have this meta information.
Know all Url rewrite tricks in Wordpress
Know all Url rewrite tricks in Wordpress
Comments
Post a Comment