use query string in URL to display content on the page

I’d like to say something on my page based on what page the person got there from. I can set up the link to that page to be:

www.example.com/page?parameter=myparameter

Is there a way I can access that parameter so that I can have it show on the page, somewhere in my content?

Related posts

3 comments

  1. Per the OP’s answer within their question:

    With your help and some Googling, I put together a shortcode that returns the value of any url parameter. Here it is:

    //THIS IS A CUSTOM SHORTCODE TO DISPLAY A PARAMETER FROM THE URL
    function URLParam( $atts ) {  
        extract( shortcode_atts( array(
            'param' => 'param',
        ), $atts ) );
        return $_GET[$param];  
    }
    add_shortcode('URLParam', 'URLParam'); 
    

    I use the shortcode like this to get the trip_type from my URL:

    [URLParam param='trip_type']
    
  2. You could use a PHP session, look in the query object for the request, or use $_GET with your url, but it’s not for sensitive information…

    Something like this;

    Grab the trip name from the URL

    $tripname = $_GET['tripname'];

    Use it in your heading;

    if(isset($tripname)) echo '<h1>Plan Your Trip To ' .$tripname. '</h1>';

  3. Here’s another great way to accomplish this. This won’t require shortcodes and will automatically update each page you create where there parameter “trip” is present!

    1) Navigate to your theme folder and open functions.php (or create it if it’s missing)

    2) Add the following code and save:

    <?php 
        add_filter( 'the_content', 'my_trip_filter' );
    
        function my_trip_filter( $content ) {
            if ( isset($_REQUEST['trip']) && is_single() ) {
                $content = "<h1>Fill out this form to register for the " . $_REQUEST['trip'] . " trip</h1>" . $content;
            }
    
            return $content;
    
        }
    ?>
    

    This code uses the_content filter to override each time you use the function the_content() function to print your blog information. It detects whether or not the page requested is a single page/post and not the archive. Additional logic or overrides can be added to it. Just make sure you return $content and whatever message you desire will be returned to the screen.

    Enjoy!

Comments are closed.