Last active
November 23, 2016 18:53
-
-
Save keesiemeijer/05c84d64d3d34408be3e71e2b435ecee to your computer and use it in GitHub Desktop.
Only allow one shortcode in post 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
add_filter( 'the_content', 'MyTheme_do_first_shortcode' ); | |
function MyTheme_do_first_shortcode( $content ) { | |
// EDIT: Shortcode name (without brackets) | |
$shortcode = 'shortcode-name'; | |
if ( has_shortcode( $content, $shortcode ) ) { | |
$regex = get_shortcode_regex( array( $shortcode ) ); | |
$i = 0; | |
$content = preg_replace_callback( "/$regex/", function( $m ) use( &$i ) { | |
return MyTheme_do_shortcode_tag( $m, $i++ ); | |
}, $content ); | |
} | |
return $content; | |
} | |
function MyTheme_do_shortcode_tag( $m, $i ) { | |
global $shortcode_tags; | |
// allow [[foo]] syntax for escaping a tag | |
if ( $m[1] == '[' && $m[6] == ']' ) { | |
return substr( $m[0], 1, -1 ); | |
} | |
$tag = $m[2]; | |
$attr = shortcode_parse_atts( $m[3] ); | |
// Don't do shortcode if the index is above 0 | |
if ( $i ) { | |
return ''; | |
} | |
if ( ! is_callable( $shortcode_tags[ $tag ] ) ) { | |
/* translators: %s: shortcode tag */ | |
$message = sprintf( __( 'Attempting to parse a shortcode without a valid callback: %s' ), $tag ); | |
_doing_it_wrong( __FUNCTION__, $message, '4.3.0' ); | |
return $m[0]; | |
} | |
if ( isset( $m[5] ) ) { | |
// enclosing tag - extra parameter | |
return $m[1] . call_user_func( $shortcode_tags[$tag], $attr, $m[5], $tag ) . $m[6]; | |
} else { | |
// self-closing tag | |
return $m[1] . call_user_func( $shortcode_tags[$tag], $attr, null, $tag ) . $m[6]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Edit the shortcode name in line 6