I am using wordpress and woocommerce ( an e-commerce plugin) to customize a shopping cart. Within my functions.php I am storing data in a variable like so:
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
function add_custom_price( $cart_object ) {
foreach ( $cart_object->cart_contents as $key => $value ) {
$newVar = $value['data']->price;
}
}
I need to be able to use $newVar
in a different function so I can echo the result on a different area of the page. For instance, if I had the following function, how would I use $newVar
within it?
add_action( 'another_area', 'function_name' );
function function_name() {
echo $newVar;
}
How can I do this?
You need to instantiate (create) $newVar outside of the function first. Then it will be view-able by your other function. You see, scope determines what objects can be seen other objects. If you create a variable within a function, it will only be usable from within that function.
PHP Reference Assignment Operator In PHP, the reference assignment operator ( =& ) is used to create a new variable as an alias to an existing spot in memory. In other words, the reference assignment operator ( =& ) creates two variable names which point to the same value.
Open your web browser and type your localhost address followed by '\form1. php'. Output: It will open your form like this, asked information will be passed to the PHP page linked with the form (action=”form2. php”) with the use of the POST method.
You could make the variable global:
function add_custom_price( $cart_object ) {
global $newVar;
foreach ( $cart_object->cart_contents as $key => $value ) {
$newVar = $value['data']->price;
}
}
function function_name() {
global $newVar;
echo $newVar;
}
Or, if $newVar
is already available in the global scope you could do:
function function_name($newVar) {
echo $newVar;
}
// Add the hook
add_action( 'another_area', 'function_name' );
// Trigger the hook with the $newVar;
do_action('another_area', $newVar);
Any reason why you can't call your function from within your foreach loop?
function add_custom_price( $cart_object ) {
foreach ( $cart_object->cart_contents as $key => $value ) {
$newVar = $value['data']->price;
function_name($newVar);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With