0

please forgive me I'm relatively new to PHP...

I would like to create a shortcode called [city-name] and have tried placing the following code in my functions.php file:

function get_city_name() {
return $current_cityinfo['cityname'];
}
add_shortcode( 'city-name', 'get_city_name' );

Then entered the [city-name] shortcode into a page to test and there is no luck...

Is there something wrong with my syntax.... I have entered the following into my category pages and that works absolutely fine:

<h1 class="loop-title"><?php single_cat_title(); ?> - <?php echo $current_cityinfo['cityname'];?></h1>

I hope someone can help me out here... been searching for over 2 hrs now and no luck so thanks in advance!

JAke

1
  • 2
    You have to define the variable $current_cityinfo inside get_city_name(), before you can use it - it is a PHP scope problem, read up on it. If it is a global variable, then do it by using the key word. Otherwise you have to use whatever logic is behind the variable. Commented Mar 24, 2015 at 13:29

3 Answers 3

1

You need to get $current_cityinfo first. As in:

$current_cityinfo = get_option('current_cityinfo');

Or add this code:

global $current_cityinfo;

above your return line.

2
  • 1
    There is no information, indeed, but it usually is. It's not a meta value and it's not a custom category value, so it must be an option.
    – Ciprian
    Commented Mar 24, 2015 at 13:35
  • I agree the original post lacks some information, but the user is "relatively new to PHP" so I suppose WordPress is not a strong feat.
    – Ciprian
    Commented Mar 24, 2015 at 13:51
1

You should be passing the 'cityname' to your function:

function get_city_name($cityname) {
return $cityname;
}
add_shortcode( 'city-name', 'get_city_name' );

Your shortcode would then look like:

[city-name cityname="London"]

chances are that your function will return an array, but this should help you move forward

0

Okay, so found the solution (sorry for the delay)

I had to put this:

// Add Shortcode
function city_name() {

 global $current_cityinfo; return ' '.$current_cityinfo['cityname'];

}

add_shortcode( 'city name', 'city_name' );
1
  • I'm glad it worked for you. Can you mark the correct answer?
    – Ciprian
    Commented Mar 30, 2015 at 15:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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