golaz
golaz

Reputation: 71

Why is my function in Wordpress not working?

Why not work my function in wordpress?

My code

add_post_meta( $ids, 'price', $price, true );
$price_add = get_post_meta($id, 'price', true);

function myprice(){
    if ($price_add != ' '){
        echo $price_add." Euro";
    }
    else {
        echo "None";
    }
}

I try use if (isset($price_add)) but not work.

I want to show price introduced in or show text "None".

Upvotes: 0

Views: 75

Answers (1)

IMSoP
IMSoP

Reputation: 97708

You are attempting to use a variable which is not "in scope". You might want to read the PHP manual page on variable scope.

A function is a reusable piece of code, with input and output, and in PHP variables are "scoped" (visible) to the function they are declared in. (The main exception is global variables, which are usually frowned on as they make code hard to read, reuse, and test; static variables and object members work a bit differently.)

In your case, you want a function which takes as input a price, and echoes that price if it is not an empty string (or, as you've written it, a single space); you might define that like this:

function myprice($price_to_display) {
    if ($price_to_display != ' '){
        echo $price_to_display." Euro";
    }
    else {
        echo "None";
    }
}

You then call that somewhere else, passing in the value you want to display, like this:

$price_add = get_post_meta($id, 'price', true);
myprice($price_add);

Note that I've named the variable in the function something different for clarity; you could call it $price_add, but that wouldn't make it connected to the other variable called $price_add in any special way.

[Edited to add...] In fact, you don't need to have a variable at all when you are calling the function - what you are providing is a value for the input parameter. So you could also write it like this:

myprice( get_post_meta($id, 'price', true) );

Upvotes: 2

Related Questions