Hack: Look For And Use a URL Query Parameter

You see webpages everywhere using things in their URLs like ?something=xyz. These parameters are then passed into the page and used for various things. You can easily use this same technique to pass in information to your WordPress posts.

Here is an example script that you can add to your functions.php or custom plugin. It gets the parameter something and just appends the value to the end of the content.

add_filter('the_content', 'wpfilter_content_query');
function wpfilter_content_query($content) {
	return $content.$_GET['something'];
}

This is just a demonstration. You can see that the PHP $_GET array is used to access these URL parameters. You can use them in any filter or action to test for things and perform different actions. For instance, if you have code that inserts ads, you can test $_GET[‘noads’] != ‘1’ to see if ?noads=1 is present in the URL and then not display the ads in that case.

Or, you could use $_GET[‘dataid’] to grab the value of a parameter and look up an item in your custom database to display in the post or page. So a single post can then show different things depending on the value of ?dataid= in the URL.

Note that you can include multiple parameters in your URL by putting a & in between them, like ?dataid=76&noads=1.

2 Replies to “Hack: Look For And Use a URL Query Parameter”

  1. I’m assuming that there is no data sanitization in this tip so you’d have to ensure there is no nasty code in the url before running it in your WordPress code?

  2. Andy: Right. You’d want to use the data wisely. I wouldn’t ever “run it” in your code, but instead use it as simply data. Like if dataid represented a number, such as a two-letter state code, and you then looked up the state in a database. So if you don’t get a two-letter code back, then show an error.

Leave a Reply

Your email address will not be published. Required fields are marked *