Tell me more ×
WordPress Answers 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

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

Questions on WordPress Answers are expected to relate to WordPress within the scope defined in the FAQ. 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 closed questions here.

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

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