I need a list of every shortcode inside the content. Is there any way to list them?
This is what I need:
$str = '[term value="Value" id="600"][term value="Term" id="609"]';
So every shortcode should be inside the $str
.
I found a code snippet to check if there is a shortcode. But how can I display them all?
$content = 'This is some text, (perhaps pulled via $post->post_content). It has a [gallery] shortcode.';
if( has_shortcode( $content, 'gallery' ) ) {
// The content has a [gallery] short code, so this check returned true.
}
I need a list of every shortcode inside the content. Is there any way to list them?
This is what I need:
$str = '[term value="Value" id="600"][term value="Term" id="609"]';
So every shortcode should be inside the $str
.
I found a code snippet to check if there is a shortcode. But how can I display them all?
$content = 'This is some text, (perhaps pulled via $post->post_content). It has a [gallery] shortcode.';
if( has_shortcode( $content, 'gallery' ) ) {
// The content has a [gallery] short code, so this check returned true.
}
Share
Improve this question
asked Jun 18, 2019 at 13:54
CrayCray
1452 silver badges11 bronze badges
3 Answers
Reset to default 4Here's one way:
You can look at has_shortcode() and find the parsing there:
preg_match_all(
'/' . get_shortcode_regex() . '/',
$content,
$matches,
PREG_SET_ORDER
);
using the get_shortcode_regex() function for the regex pattern.
For non empty matches, you can then loop through them and collect the full shortcode matches with:
$shortcodes = [];
foreach( $matches as $shortcode ) {
$shortcodes[] = $shortcode[0];
}
Finally you format the output to your needs, e.g.:
echo join( '', $shortcodes );
PS: It can be handy to wrap this into your custom function.
If you only need the Shortcodes without the attributes, you can use this function:
function get_used_shortcodes( $content) {
global $shortcode_tags;
if ( false === strpos( $content, '[' ) ) {
return array();
}
if ( empty( $shortcode_tags ) || ! is_array( $shortcode_tags ) ) {
return array();
}
// Find all registered tag names in $content.
preg_match_all( '@\[([^<>&/\[\]\x00-\x20=]++)@', $content, $matches );
$tagnames = array_intersect( array_keys( $shortcode_tags ), $matches[1] );
return $tagnames;
}
You will get an array of all shortcodes, that are used within the content you give it.
Love @birgire's accepted answer, but a limitation of it is that any nested shortcodes are missed. You can overcome this by creating a simple walker:
function all_shortcodes($content) {
$return = array();
preg_match_all(
'/' . get_shortcode_regex() . '/',
$content,
$shortcodes,
PREG_SET_ORDER
);
if (!empty($shortcodes)) {
foreach ($shortcodes as $shortcode) {
$return[] = $shortcode;
$return = array_merge($return, all_shortcodes($shortcode[5]));
}
}
return $return;
}
$shortcodes_including_nested = all_shortcodes($post_content);