2

I have wordpress custom template page test.php in which I want to pass variable throuh url like,

http://localhost/wordpress/test?date=2017&postid=11&title=some-title

in this format,

http://localhost/wordpress/test/2017/11/some-title

and grab the parameter from the url.

I have followed this link, but couldn't produce the result as I have desired.

Is there another way to achieve the desired result as I have mentioned??? I am pretty newbie to wordpress theme development.

2
  • 1
    Would be interested in "why". Given I have some experience with WP, and have simply never had to do it. Of course you may have a reason, or you might be missing an easier way to achieve your end result. Commented Mar 27, 2017 at 17:25
  • 1
    You could use your web server (apache or nginx) rewrite rules to rewrite the path to the query parameters. That way the user will see the second format but in php you will have the first format with query parameters and use the normal get_query_var from wordpress Commented Mar 27, 2017 at 20:36

1 Answer 1

3

Well, as suggested by @vl4d1m1r4 , I have used the web server(in my case apache) rewrite rule to rewrite the path. Some-what I have achieved the desired result. In function.php I have written the following code to update the rewrite rule in wordpress(.htaccess)

add_filter( 'query_vars', 'add_custom_query_vars' );
function add_custom_query_vars( $vars )
{
    array_push($vars, "test_year", "test_postid", "test_title");
    return $vars;
}
function custom_rewrite_rule()
{
    add_rewrite_rule('^test/([^/]*)/([^/]*)/([^/]*)?','index.php?pagename=test&test_year=$matches[1]&test_postid=$matches[2]&test_title=$matches[3]','top');
}
add_action('init', 'custom_rewrite_rule');

After adding the above code, I have re-saved the permalink settings(setting>>permalink)

To Get the parameter in custom-template-page i.e test.php. I have used the following query.

echo get_query_var('test_title');
echo get_query_var('test_postid');
echo get_query_var('test_year');
Sign up to request clarification or add additional context in comments.

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.