Skip to content

Instantly share code, notes, and snippets.

@5ally
Created June 14, 2022 02:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 5ally/a2f8390134f48ca3754ced3b770fb9fc to your computer and use it in GitHub Desktop.
Save 5ally/a2f8390134f48ca3754ced3b770fb9fc to your computer and use it in GitHub Desktop.
my_get_shortcode_atts() - see https://wordpress.stackexchange.com/a/406679/137402 for details
<?php
/*
* Get the attributes, if any, of the first shortcode with the tag $shortcode_id,
* in the current post.
*
* @param string $shortcode_id Shortcode tag like "foo", foo_bar or my-shortcode.
* @return array|string|false Returns an array of attributes if the shortcode is found, and
* it has one or more attributes, e.g. array( 'att1' => 'value' ).
* '' (i.e. empty string) is returned if there are no attributes.
*/
function my_get_shortcode_atts( $shortcode_id ) {
// get the content before the loop
// Honestly though, I (Sally) would use a $content or $text, or $post parameter..
// and FYI, get_queried_object() can be used to target the current page you're on.
$fst_content = get_the_content( null, false, get_post() );
if ( ! $fst_content ) {
return false;
}
// retrieve cached attributes, if any
$cache_key = 'shortcode_atts-' . md5( "$shortcode_id:$fst_content" );
$shortcode_atts = wp_cache_get( $cache_key );
if ( is_array( $shortcode_atts ) ) {
// return the 1st array item, if set
return $shortcode_atts[0] ?? false;
}
// extract shortcode attributes - $matches[3] is the attributes string, whereas
// $matches[2] is the shortcode tag
preg_match_all( '/' . get_shortcode_regex() . '/s', $fst_content , $matches );
$shortcode_atts = array();
if ( isset( $matches[2] ) ) {
foreach ( (array) $matches[2] as $key => $value ) {
if ( $shortcode_id === $value ) {
$shortcode_atts[] = shortcode_parse_atts( $matches[3][ $key ] );
}
}
// cache all the attributes from $matches[3]
wp_cache_set( $cache_key, $shortcode_atts );
}
// return the 1st array item, if set
return $shortcode_atts[0] ?? false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment