There is no definitive way of doing that in WordPress, but here are some options for you:
-
Use a global variable to store the reference list, i.e. the content as in
[ref]content here[/ref]
. But I personally don’t recommend and wouldn’t be using global variable. -
Use a custom PHP class and add the shortcode functions as methods in that class, then use a property (e.g.
private $ref_list = [];
) to store the reference list. So for example inside theref_shortcode()
method, you could do$this->ref_list[] = $content;
. -
Use the object caching API in WordPress, e.g. use
wp_cache_set()
to store the reference list.
And I’m not asking you to use the third option above, but since your code originally not in a PHP class, then here’s a working example using the object caching API:
function ref_shortcode( $atts = array(), $content = null ) {
if ( ! empty( $content ) ) {
$post_id = get_the_ID();
// Retrieve current list of references for the current post.
$refs = wp_cache_get( "post_{$post_id}_references" );
$refs = is_array( $refs ) ? $refs : array();
// Then add the current reference to the list.
$refs[] = $content;
wp_cache_set( "post_{$post_id}_references", $refs );
$j = count( $refs );
return "<a href="#ref-$post_id-$j"><sup>[$j]</sup></a>";
}
return '';
}
add_shortcode( 'ref', 'ref_shortcode' );
function references_shortcode( $atts = array(), $content = null ) {
$post_id = get_the_ID();
$refs = (array) wp_cache_get( "post_{$post_id}_references" );
$output="";
if ( ! empty( $refs ) ) {
$output="<h3>References</h3>";
$output .= '<ul>';
foreach ( $refs as $i => $ref ) {
$j = $i + 1;
$output .= "<li id='ref-$post_id-$j'>$ref</li>";
}
$output .= '</ul>';
}
return $output;
}
add_shortcode( 'references' , 'references_shortcode' );