1

Learning with WP REST I'm unsure how to properly pass what is typically at the beginning of a PHP page form to WP_REST_Response. For example:

At the beginning of page-foobar.php if I have:

// IP ADDRESS
function ipAddress() {
    if (isset($_SERVER['REMOTE_ADDR'])) :
        $ip_address = $_SERVER['REMOTE_ADDR'];
    else :
        $ip_address = "undefined";
    endif;
    return $ip_address;
}
/*
    Template Name: Foobar
*/

and need to use $ip_address in:

function foobar(\WP_REST_Request $request) {
    if ($ip_address == "undefined") :
        return new WP_Error( 'bad_ip', 'No IP found', array( 'status' => 404 ) );
    endif;
}

how would I go about doing that? When I searched I ran across:

Pass a Variable from one file to another in WordPress but I dont think it would be a good idea to pass as a global. Further researching Passing variables between files in WordPress or PHP but I've already called the template in functions.php. How can I pass a function from the template to the function request if it's stored in a different file?

  • You might want to take a look into the wp_cache_set(); function. – Jack Johansson Aug 16 '17 at 17:18
  • Should you not define ipAddress() in functions.php? Page templates are not a good place to define things, they're for using things – Tom J Nowell Aug 16 '17 at 17:28
2

My approach would be, to declare the function in functions.php and then call it whenever you need.

Since you are trying to use superglobals, you can access them anywhere. Move the code from your page-foobar.php to your theme's functions.php, and use this whenever you need to access it:

ipAddress();

So, in your REST function you can have:

function foobar(\WP_REST_Request $request) {
    $ip_address = ipAddress();
    if ($ip_address == "undefined") :
        return new WP_Error( 'bad_ip', 'No IP found', array( 'status' => 404 ) );
    endif;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.