Passing variables to new page

Edit: OK, I get what you’re trying to do a little better. This should help get you there.

  1. Cache the data that you are going to want. You’ll go over your API limit quickly if you query Yelp on every page load – not to mention slowing your site down terribly.

    function yelplist() {
    
        $pizza_joints = wp_cache_get( 'pizza-joints' );
    
        if ( !$pizza_joints ) {
    
            require_once ('/lib/OAuth.php'); 
            require_once ('yelp.php'); 
            require_once(ABSPATH.'/wp-admin/includes/taxonomy.php');
    
            $yelpstring = file_get_contents('http://api.yelp.com/business_review_search?term=pizza&location=Los%20Angeles&ywsid=xxxxxxxxxxxxxxxxxxx');
    
            $obj = json_decode($yelpstring);
    
            $pizza_joints = array();
    
            foreach( $obj->businesses as $business ) {
    
                $path = trim( '' . parse_url($business->url, PHP_URL_PATH) . '', '/biz' );
                $pizza_joints[ $path ] = $business;
    
            }
    
            wp_cache_set( 'pizza-joints', $pizza_joints );
    
        }
    
        return $pizza_joints;
    
    }
    
  2. Create a page for your single pizza joint reviews and set up a custom page template for it. Keep track of the page ID for that page. I’ll say for the rest of my examples that this page has an ID of 50 and the page template its using is single-pizza.php.

  3. ON your front page: when you want to link to individual pizza joint pages, link to that page with an additional variable passed reflecting the individual joint you want to show. Use the function add_query_arg to generate the url to pass that variable:

    $pizza_joints = yelplist();
    
    foreach ( $pizza_joints as $path => $pizza_joint ) {
    
        echo '<p><a href="' 
            . add_query_arg( 'pizza', $path, get_permalink( 50 ) )
            . '">' . $pizza_joint->name . '</a></p>';
    
    }
    
  4. Now when that link is clicked, the viewer will go to the page defined by the template single-pizza.php. In that template, you can access the variable passed by checking the contents of $_GET[‘pizza’].

    /*
    
    Template Name: Single Pizza Joint Data
    
    */
    
    $pizza_joints = yelplist();
    
    if ( isset( $_GET['pizza'] ) &&  array_key_exists( $_GET['pizza'], $pizza_joints ) ) {
    
        $this_business = $pizza_joints[ $_GET['pizza'] ];
    
        echo '<img src="' . $this_business->photo_url .'">';
        echo '<h2>' . $this_business->name .'</h2>';
        echo '<h4>' . $this_business->phone .'</h2>';
    
    } else { 
    
        // either no variable was passed, or it doesn't match a business in the list
    
        wp_redirect( home_url() );
    
            }
    

Leave a Comment