Skip to content

Instantly share code, notes, and snippets.

@musen
Last active December 22, 2015 11:51
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 musen/9243534edb429386d6a5 to your computer and use it in GitHub Desktop.
Save musen/9243534edb429386d6a5 to your computer and use it in GitHub Desktop.
Extracts a shortcode tag from a post content and returns the content with target shortcode tag stripped out.
<?php
/**
* Based on:
* https://codex.wordpress.org/Function_Reference/get_shortcode_regex
*/
function extract_shortcode($content, $tag) {
$shortcode_match = false;
$pattern = get_shortcode_regex();
if ( preg_match_all( '/'. $pattern .'/s', $content, $matches )
&& array_key_exists( 2, $matches )
&& in_array( $tag, $matches[2] ) )
{
$tag_index = array_search($tag, $matches[2]);
$complete_shortcode = $matches[0][$tag_index];
return $complete_shortcode;
}
}
/**
* @param string $code name of the shortcode
* @param string $content
* @return string content with shortcode striped
* @usage $content = strip_shortcode('gallery', $content);
*/
function strip_shortcode($code, $content)
{
global $shortcode_tags;
$stack = $shortcode_tags;
$shortcode_tags = array($code => 1);
$content = strip_shortcodes($content);
$shortcode_tags = $stack;
return $content;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment