Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save MikeRogers0/8617550 to your computer and use it in GitHub Desktop.
Save MikeRogers0/8617550 to your computer and use it in GitHub Desktop.
PHP Variable Scope with Wordpress shortcode attributes
<?php
// I have a function, embedVine(), which is a Wordpress shortcode. It uses one attribute, $id which I've assigned to $vine_id to avoid confusion ($post_id etc). This shortcode takes the ID (Vine IDs are the ending of the Vine URL, e.g http://vine.co/v/hx9LlrZxdqV, the id = hx9LlrZxdqV) and embed's the Vine within a Wordpress post. The shortcode markup is [vine id='...'].
$vine_id = false;
global $vine_id;
function embedVine($atts) {
global $vine_id;
extract(shortcode_atts(array(
"id" => ''
), $atts));
$vine_id = $id;
// I'm then doing a whole load of stuff involving $vine_id, including using it as a parameter to pass to different functions I've written that are separate to this function.
$output = "...";
return $output;
} add_shortcode("vine", "embedVine");
// I then have another function, vineThumb() which when executed, needs to use the $vine_id variable as it's parameter. However, the $vine_id variable is defined within the function, so when I try to call it outside of the function, it appears undefined. How can I access $vine_id from outside of the function?
function vineThumb($id) {
global $vine_id;
if($vine_id){
$id = $vine_id
}
$vine = file_get_contents("http://vine.co/v/{$id}");
return $vine;
// of course, it's a lot more complicated than this but for the sake of this, it works.
} vineThumb($vine_id);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment