0

I'm searching for a way to pass a variable from a custom Wordpress page template to my child theme functions.php file. I have the wrong scope and I'm completely lost. I'm trying to generate a google map with user submitted data here: http://cheryllynch.com/homevalue/

Do I need to write to the mySQL database to do this? Should I brake the rules and use a global variable?

<!--HomeValue.php Template-->
$latitude = $xml[$i]->response->results->result->address->latitude; 
$_POST['latitude'];

<!--functions.php--> 
    wp_enqueue_script( //From jqueryui.com copy CDN (or download)
    'jqueryui',
    '//code.jquery.com/ui/1.10.3/jquery-ui.js',
    array('jquery')
    );  //End of enqueue jQuery UI


    wp_enqueue_script( 'extra js', get_stylesheet_directory_uri() . '/js/extra.js' );

    $datatoBePassed = array(
    'hvuri'  => get_stylesheet_directory_uri() . '/page-homevalue.php',
    'latitude' => __(latitude), 
    'longitude' => __(longitude)

    );
    wp_localize_script( 'extra js', 'gmap_php_vars', $datatoBePassed );
    }
}
add_action( 'wp_enqueue_scripts', 'cheryllynch_sheeva_child_scripts' );
  • How is the user submitted data stored? – czerspalace Jul 24 '15 at 21:29
  • It's just a _POST to the same page. – Brad Jul 25 '15 at 0:58
  • 1
    Please edit that code into the question body. – s_ha_dum Jul 25 '15 at 3:48
0

... from a custom Wordpress page template to my child theme functions.php file...

You can't. And a global variable won't help. The theme's functions.php file loads first, before any other templates load. You can't pass variables backwards to something that has already loaded.

What I think you want to do, based on what your code appears to be trying to do, is embed your data in the template file:

wp_enqueue_script( 'extra js', get_stylesheet_directory_uri() . '/js/extra.js' );

$datatoBePassed = array(
  'hvuri'  => get_stylesheet_directory_uri() . '/page-homevalue.php',
  'latitude' => __(latitude), 
  'longitude' => __(longitude)
);
wp_localize_script( 'extra js', 'gmap_php_vars', $datatoBePassed );

Then have your Javascript look for that data via the gmap_php_vars Javascript variable.

Proof of concept:

function grab_gmap() { ?>
  <script type="text/javascript">
    alert(gmap_php_vars.hvuri); 
  </script><?php
}
add_action('wp_footer','grab_gmap');

In effect you are doing more or less the opposite of what you are trying to do.

In practice, you should not really shove Javascript into the page like that. The function responsible should probably be in the extra.js file you enqueue.

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.