Site icon Hip-Hop Website Design and Development

Adding to the_content or a variable from within a shortcode function

I’ve created a custom shortcode to add pop-up definitions to selected vocabulary terms. The shortcode looks like this:

[glossary term="data breach"]data breaches[/glossary]

The function searches posts in a custom post type called ‘glossary-term’ for the term’s definition, prints it in a div, and turns the enclosed text into a link to that div:

function glossary_shortcode( $atts = array(), $shortcode_content = null ) {
    
    // parameters
    extract(shortcode_atts(array(
        'term' => null
    ), $atts));
    
    $glossary_term_object = get_page_by_title($term, 'OBJECT', 'glossary-term');

   // print definition in popup div
    echo '<div id="glossary-popup-' . $glossary_term_object->post_name . '" class="glossary_popup"><h4>' . $glossary_term_object->post_title . '</h4>' . wpautop( $glossary_term_object->post_content ) . '<div class="ctas"><a href="">Visit Glossary</a><a href="#">Close</a></div></div>';

    // return link to definition popup
    return '<a href="#glossary-popup-' . $glossary_term_object->post_name . '">' . $shortcode_content . '</a>';
    
}

add_shortcode('glossary', 'glossary_shortcode');

Rather than echo the definition pop-up, I’d like to have all the definitions created by this shortcode (which may be used several times on a page) collected into their own div at the end of the main page content.

Any ideas how to accomplish this?