Categories
Accelerated Mobile Pages (AMP)

How to check if the current page is an AMP page in WordPress

If you are using an AMP-compatible theme and using the AMP plugin for AMP implementation, then sometimes you may need to check if the current page is an AMP page request or a normal page request.

AMP plugin has a built-in function that you can use to do just that. Its amp_is_request(). This function allows you to check whether the current page is an AMP request or a normal request. I have listed a few examples below with the implementation of amp_is_rquest() to achieve a few features.

Load a different sidebar for AMP pages

You may want to load a different sidebar specifically for AMP pages so that it will have complete AMP-compatible code. Here is an example how you can achieve that :

Create a custom function to check if the current AMP request that avoids errors when the AMP plugin is disabled. Add the following code in the functions.php file to do that.

// Add this function in functions.php file
// custom function to check if amp_is_request exists so that the site doesn't throw error when AMP plugin is disabled.
function wptips_is_amp() {
  if ( function_exists( 'amp_is_request' ) ):
    return amp_is_request();
  else :
    return false;
  endif;
}

Create a custom AMP sidebar and call the sidebar if it’s an AMP request using the newly defined custom function.

// Register custom AMP Sidebar ( add this code in functions.php file )
		register_sidebar(
		array(
			'name'          => __( 'AMP Sidebar', 'wptips' ),
			'id'            => 'amp-sidebar',
			'description'   => __( 'Add widgets here to appear in AMP site sidebar.', 'wptips' ),
			'before_widget' => '<section id="%1$s" class="widget %2$s">',
			'after_widget'  => '</section>',
			'before_title'  => '<div class="widget-title">',
			'after_title'   => '</div>',
		)
	);

// Add this code in your sidebar.php or any other sidebar file where you want to implement custom sidebar for AMP version of the site.
if ( wpb_is_amp() ): dynamic_sidebar( 'amp-sidebar' );	else:	dynamic_sidebar( 'main-sidebar' ); endif;

Note: The function is_amp_endpoint() is deprecated, and you should switch to amp_is_rquest() if you are using the latest version of the AMP plugin.

Feel free to share your question or any issue that you need help with related AMP implementation in your webstie.

By Murali Kumar

I am a Full Stack Web Developer with over 12 years of experience. I love WordPress & WooCommerce.

If you need help of a WordPress developer for your website, get in touch now!.

Follow me on Twitter : @geekz

Leave a Reply

Your email address will not be published. Required fields are marked *