-1

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?

2

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

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