Shortcodes and a list of IDs?

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.

Read More

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
} 

Related posts

Leave a Reply

1 comment

  1. explode will be your best option. WordPress has a few built in functions to handle arrays of function arguments (wp_parse_args and shortcode_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:

    function video_vote($atts) {  
        extract(shortcode_atts(array(
            'users' => null
        ), $atts));
    
    
        $user_ids = explode(",", strval($users));
    
        $videos = array();
        foreach ($user_ids as $id) {
            $videos[] = get_video_vote_by_uid($id); // Assuming you have a function like this
        }
    
        return implode("nn", $videos);
    }
    

    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 example get_video_vote_for_users which will take a user list (preferably string or array parsed by wp_parse_args) and in turn iterate the users and call get_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.