Created
September 8, 2015 18:07
-
-
Save mrbobbybryant/a18588f86b12fa71224b to your computer and use it in GitHub Desktop.
Extract Shortcode Attributes for a given shortcode on save_post.
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 | |
/** | |
* Extracts Shortcode Attributes from the post content | |
* @param $content | |
* | |
* @uses get_shortcode_regex | |
* @uses shortcode_parse_atts | |
* | |
* @return array | |
*/ | |
function parse_shortcode_atts( $content, $shortcode ) { | |
//Returns a sting consisting of all registered shortcodes. | |
$pattern = get_shortcode_regex(); | |
//Checks the post content to see if any shortcodes are present. | |
$shortcodes = preg_match_all( '/'. $pattern .'/s', $content, $matches ); | |
//Check to see which key our Attributes are sotred in. | |
$shortcode_key = array_search( $shortcode, $matches[2] ); | |
//Create an new array of atts for our shortcode only. | |
$shortcode_atts[] = $matches[3][$shortcode_key]; | |
//Ensure we don't have an empty strings | |
$shortcode_atts= array_filter( $shortcode_atts ); | |
if ( ! empty( $shortcode_atts ) ) { | |
//Pull out shortcode attributes based on the above key. | |
$shortcode_atts = shortcode_parse_atts( implode( ',', $shortcode_atts ) ); | |
//Remove random commas from last value | |
$shortcode_atts = array_map( function ( $att ) { | |
return $att = str_replace( ',', '', $att ); | |
}, $shortcode_atts ); | |
$tags = array(); | |
foreach ( $shortcode_atts as $atts ) { | |
$temp = explode( '=', $atts ); | |
$tags[ $temp[0] ] = str_replace( '"', '', $temp[1] ); | |
} | |
return $tags; | |
} | |
//If no attributes are returned, then an ID Att isn't present. | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment