Skip to content

Instantly share code, notes, and snippets.

@keesiemeijer
Last active November 23, 2016 18:53
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 keesiemeijer/05c84d64d3d34408be3e71e2b435ecee to your computer and use it in GitHub Desktop.
Save keesiemeijer/05c84d64d3d34408be3e71e2b435ecee to your computer and use it in GitHub Desktop.
Only allow one shortcode in post content
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];
}
}
@keesiemeijer
Copy link
Author

Edit the shortcode name in line 6

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment