Passing a shortcode attribute to a sub-function

There are different ways to get the result. You can use a class, store the div content in a class or instance variable and output it when needed.

As alternative you can use a function with a static variable, to hold the content.

I’ll use this second alternative, converting it in a class is an exercise for you 😉

In addiction you can use the core 'wp_footer' hook to output the content, in this way you don’t have to add an additional hook, nor use a template tag.

function reveal_setup($atts = array(), $content="") {
  // Setup the static variable. Use an array to allow multiple calls per page
  static $the_modals = array();
  // if the function is called from wp_footer hook
  if ( current_filter() === 'wp_footer' ) {
    if ( is_array($the_modals) && ! empty($the_modals) ) {
      foreach( $the_modals as $amodal ) {
        echo $amodal;
      }
    }
  // if the function is called from shortcode
  } else {
    // Get the attributes
    $atts = shortcode_atts(
      array( 'size' => 'medium', 'slug' => 'dummy','bg' => 'reveal-modal' ),
      $atts,
      'reveal' // enable filtering
    );
    // prepare the_modal link
    $modal_link  = '<a href="#" data-reveal-id="' . $atts['slug'] . '">';
    $modal_link .= $content;
    $modal_link .= '</a>';
    // prepare the_modal content
    $modal_format="<div id="%s" class="%s %s" data-reveal>";
    $the_modal = sprintf( $modal_format, $atts['slug'], $atts['size'], $atts['bg'] );
    if ( $atts['slug'] == 'dummy' ) {
      $the_modal .= 'reminder/dummy content goes here';
    } else {
      $the_modal .= 'post loop based on page slug goes here';
    }
    $the_modal .= '</div>';
    // save the modal content in the static modals array
    $the_modals[] = $the_modal;
    // add the present function to wp_footer hook if it is not already added
    if ( ! has_action('wp_footer', __FUNCTION__) ) {
      add_action( 'wp_footer', __FUNCTION__ );
    }
    // return the modal link
    return $modal_link;
  }
}

add_shortcode('reveal', 'reveal_setup');

That’s all. Untested.

PS: extract usage is a bad practice, (although I know it’s largely used in core code and in Codex examples…)

Leave a Comment