Last active
November 19, 2018 01:26
-
-
Save tomoakley/8617134 to your computer and use it in GitHub Desktop.
PHP Variable Scope with Wordpress shortcode attributes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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='...']. | |
function embedVine($atts) { | |
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) { | |
$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); | |
?> |
Line 11, where is $id
set in the first place?
@SteveEdson in the extract.
But the extract doesn't return anything?
Wordpress shortcode attributes are assigned to variables :) I know this piece works though because it's not the problem. If I tried to access $id outside of the shortcode function it still wouldn't work.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@tomoakley On the Gist edit screen, make sure to put
.php
in the 'name this gist' section and it will let you format it.