I have a custom function which defines a bunch of variables. I would like to be able to call this function from inside a loop so I can have access to all its variables, like so:


function get_album_info() {
  $album_art = wp_get_attachment_image_src( get_sub_field('album_art'), 'full' );
  $album_date = get_field('album_date');
  // ...10 more variables here


<?php while (have_posts()) : the_post(); ?>

  // Get all the variables here to use them below
  get_album_info(); ?>

  <img src="<?php echo $album_art; ?>">
  <p><?php echo $album_date; ?></p>

<?php endwhile; /* End loop */ ?>

I want to use a function here because I will be using it across several templates and don't want to have to define these multiple times. I know I can use global variables, but this requires having to include them at the top of the template, which means a lot of repetition across templates. What options are available to me?

closed as off topic by kaiser, fuxia Aug 14 '12 at 9:29

Questions on WordPress Development Stack Exchange are expected to relate to WordPress within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here. If this question can be reworded to fit the rules in the help center, please edit the question.


You could return the data and set a local variable:

function get_album_info() {
    $album = array(
        'art' => wp_get_attachment_image_src( get_sub_field('album_art'), 'full' ),
        'date' => get_field('album_date')
    return $album;

$album = get_album_info();
echo $album['art'];
echo $album['date'];

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