I’m creating a simple shortcode function and need to specify a list of IDs as a variable.
I’ve checked the Codex but I’m not sure how this is handled.
The shortcode is:
[video_vote users="13027,13023,12583"]
Is the best way to loop through them by using a split or explode on the comma or is there a WordPress-specific method?
function video_vote($atts) {
extract(shortcode_atts(array(
'users' => 'no foo'
), $atts));
return $users; // works but need to loop through the IDs
// register to vote
// selected videos
}
explode
will be your best option. WordPress has a few built in functions to handle arrays of function arguments (wp_parse_args
andshortcode_atts
for example), but nothing relating to splitting a string and iterating the result. It’s not entierly clear to me what you are trying to achieve, but let’s say you were trying to get a video for each user, then you might do this:Also, depending on your needs, you might be able to simply send the comma-separated user id string along to another function. For example many of the built in WordPress functions that uses
wp_parse_args
will accept it as an argument for the users keyword where available. In that case you’ll just let the receiving function handle the splitting/iteration instead.And off course, if you have written a function like
get_video_vote_by_uid
mentioned in my example, you could just write a wrapper for that, for exampleget_video_vote_for_users
which will take a user list (preferably string or array parsed bywp_parse_args
) and in turn iterate the users and callget_video_vote_for_users
for each user and return the result. Generally, I feel it’s best to keep your shortcode handlers as simple as possible, if not only for the fact that you might one day need to use the same code outside of the shortcode.