Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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:

functions.php

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
}

Template

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

  <?php
  // 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?

share|improve this question
add comment

closed as off topic by kaiser, toscho 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.

1 Answer

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'];
share|improve this answer
add comment

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