开发者

How to pass URL variables into a WordPress page

开发者 https://www.devze.com 2022-12-24 12:50 出处:网络
This has been asked on here (over a year ago), but apparently not answered, and WordPress is always evolvin开发者_开发技巧g so maybe theres a good solution now.I want to pass variables to a WordPress

This has been asked on here (over a year ago), but apparently not answered, and WordPress is always evolvin开发者_开发技巧g so maybe theres a good solution now. I want to pass variables to a WordPress page via the url (similar to CodeIgniter uri helper segments).

Currently I can do this...

My profile page is: http://website.com/profile

I can pass a variable like this: http://website.com/profile?username=johndoe

I want to pass the variable in like this: http://website.com/profile/johndoe or http://website.com/profile/username/johndoe

There has to be some sort of helper function, right?


I've found sort of a make shift way of doing this with PHP and a WordPress function.

Here's the lowdown. In your template code include the $wp_query global variable and then use its query property, which, is an array. One of those array indexes is called 'pagename' and what it does is return the request uri of the page in question. So suppose your url is http://website.com/profile/johndoe and your WordPress installation is in your webroot then this code:

global $wp_query;
echo $wp_query->query['pagename'] 

will putout 'profile/johndoe'.

However, if url is: http://website.com/cms/profile/johndoe which means that your WordPress install in the cms directory and not webroot, the above code will still return profile/johndoe, which means, it takes into account what the difference between the WordPress Adress and the Site Address are set to in the settings panel.

So anyways, the good part is tht you can take this output and split into an array like so:

$segments = array_explode('/', $wp_query->query['pagename']);

I believe the first segment (profile in this case would be the assigned to the first index of the array and so on.).

Anyways, it's not quite as nice as CodeIgniter but it doesn't take much code to do and it does the trick.


Assuming that your wp installation is using permalinks, so the .htaccess features, you should put on TOP of your .htaccess file the following :

Options +FollowSymlinks
RewriteEngine on
RewriteRule ^profile/(.*)$ /profile?username=$1 [NC]


Append to your .htaccess file in the root folder something like

 RewriteRule ^profile/?([_0-9a-z-]+)?/?$ http://website.com/profile?username=$1 [R=301,L]

after the other RewriteRules

0

精彩评论

暂无评论...
验证码 换一张
取 消