Skip to content

Instantly share code, notes, and snippets.

@westonruter
Last active June 2, 2021 15:45
Show Gist options
  • Save westonruter/95da1a34dd4a758e6622c6319c54a60b to your computer and use it in GitHub Desktop.
Save westonruter/95da1a34dd4a758e6622c6319c54a60b to your computer and use it in GitHub Desktop.
WordPress shortcode for conditionally showing content based on whether or not it is an AMP response.
<?php
/**
* Plugin Name: AMP is_amp_endpoint shortcode
* Description: Add a shortcode for conditionally showing content based on whether or not it is an AMP response.
* Plugin URI: https://gist.github.com/westonruter/95da1a34dd4a758e6622c6319c54a60b
* Author Name: Weston Ruter
* Author URI: https://weston.ruter.net/
* Gist Plugin URI: https://gist.github.com/westonruter/95da1a34dd4a758e6622c6319c54a60b
*/
// Allow shortcodes to run in Custom HTML widgets.
add_filter( 'widget_custom_html_content', 'do_shortcode' );
/*
* USAGE:
*
* Show content if it is an AMP page:
* [is_amp_endpoint value=true]<amp-ad>...</amp-ad>[/is_amp_endpoint]
* or
* [is_amp_endpoint true]<amp-ad>...</amp-ad>[/is_amp_endpoint]
*
* And show content if it is *not* an AMP page:
* [is_amp_endpoint value=false]<iframe class=ad></iframe>[/is_amp_endpoint]
* or
* [is_amp_endpoint false]<iframe class=ad></iframe>[/is_amp_endpoint]
*/
add_shortcode(
'is_amp_endpoint',
function( $attr, $content ) {
$value = true;
if ( isset( $attr['value'] ) ) {
$value = rest_sanitize_boolean( $attr['value'] );
} elseif ( isset( $attr[0] ) ) {
$value = rest_sanitize_boolean( $attr[0] );
}
$is_amp_endpoint = ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() );
if ( $is_amp_endpoint === $value ) {
$content = do_shortcode( $content );
} else {
$content = '';
}
return $content;
}
);
@westonruter
Copy link
Author

@westonruter
Copy link
Author

Here's an alternative which is better suited for blocks: https://gist.github.com/westonruter/0769f147e021e0ebfcb04a084987483a

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