Last active
June 2, 2021 15:45
-
-
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.
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 | |
/** | |
* 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; | |
} | |
); |
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
Installation instructions: https://gist.github.com/westonruter/6110fbc4bef0c4b8c021a112012f7e9c