Created
November 22, 2020 10:00
-
-
Save danieliser/8d398e93fcf109bec44214716f835309 to your computer and use it in GitHub Desktop.
Extracting shortcodes & attributes from content in WordPress. These helper functions can help extracting shortcodes and their attributes from WordPress content.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Extract shortcodes from content. | |
* | |
* @param string $content Content containing shortcodes. | |
* | |
* @return array Array of shortcodes found. | |
*/ | |
function get_shortcodes_from_content( $content ) { | |
$pattern = get_shortcode_regex(); | |
$shortcodes = []; | |
if ( preg_match_all( '/' . $pattern . '/s', $content, $matches ) ) { | |
foreach ( $matches[0] as $key => $value ) { | |
$shortcodes[ $key ] = [ | |
'full_text' => $value, | |
'tag' => $matches[2][ $key ], | |
'atts' => shortcode_parse_atts( $matches[3][ $key ] ), | |
'content' => $matches[5][ $key ], | |
]; | |
if ( ! empty( $shortcodes[ $key ]['atts'] ) ) { | |
foreach ( $shortcodes[ $key ]['atts'] as $attr_name => $attr_value ) { | |
// Filter numeric keys as they are valueless/truthy attributes. | |
if ( is_numeric( $attr_name ) ) { | |
$shortcodes[ $key ]['atts'][ $attr_value ] = true; | |
unset( $shortcodes[ $key ]['atts'][ $attr_name ] ); | |
} | |
} | |
} | |
} | |
} | |
return $shortcodes; | |
} | |
/** | |
* Find specific shortcodes from given content. | |
* | |
* @param string $content Content containing shortcodes. | |
* @param string|array $shortcode_tags Shortcode tags to look for. | |
* | |
* @return array Array of shortcodes found. | |
*/ | |
function find_shortcodes_in_content( $content, $shortcode_tags = [] ) { | |
if ( ! is_array( $shortcode_tags ) ) { | |
$shortcode_tags = array_map( 'trim', explode( ',', $shortcode_tags ) ); | |
} | |
$shortcodes = get_shortcodes_from_content( $content ); | |
foreach ( $shortcodes as $key => $shortcode ) { | |
if ( ! in_array( $shortcode['tag'], $shortcode_tags ) ) { | |
unset( $shortcodes[ $key ] ); | |
} | |
} | |
return $shortcodes; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment