I have two product pages of an ecommerce website: one made with Woocommerce (in WordPress) and one I coded my self in AMP.
Here is the WordPress page, and here is the AMP page. Not taking into account that the two pages are on two different subdomains, how would I redirect mobile users to the AMP version of the page ?
A similar question was asked, but it only specified how to do it for simple pages, not product pages.
Does anyone know how to that?
To answer your question, You have to hard code this following lines in your theme functions.php if you don't want to use plugin.
Following ways to make it work as per your question
Step 1: Create Metabox
//Create Metabox
function wc_49570125_register_meta_boxes() {
add_meta_box('meta-box-id', __('Mobile Version URL', 'yourtextdomain'), 'wc_49570125_my_display_callback', 'product');
}
add_action('add_meta_boxes', 'wc_49570125_register_meta_boxes');
Step 2: Add Input Field
// Add Input Field
function wc_49570125_my_display_callback($post) {
$get_id = $post->ID;
$get_value = get_post_meta($get_id, 'wc_mobile_version_url', true);
?>
<p>
<label><?php _e('Mobile URL to Redirect', 'yourtextdomain'); ?></label>
<input type="text" name="wc_mobile_version_url" value="<?php echo $get_value; ?>"/>
</p>
<?php
}
Step 3: Save the Input Field
// save input field
function wc_49570125_save_meta_box($post_id) {
$post_type = get_post_type($post_id);
if ('product' != $post_type) {
return;
}
if (isset($_POST['wc_mobile_version_url'])) {
$mobile_version = $_POST['wc_mobile_version_url'];
update_post_meta($post_id, 'wc_mobile_version_url', $mobile_version);
}
}
add_action('save_post', 'wc_49570125_save_meta_box');
Step 4: Redirect mobile users to mobile version
// redirect input field
function wc_49570125_mobile_redirect() {
global $product, $post;
if (is_product()) {
$get_id = $post->ID;
$amp_location = get_post_meta($get_id, 'wc_mobile_version_url', true);
if (wp_is_mobile() && $amp_location) {
wp_redirect($amp_location);
exit;
}
}
}
add_action('wp', 'wc_49570125_mobile_redirect');
Step 5: Add Discoverable Link for Google
function wc_49570125_amp_google_link() {
global $product, $post;
if (is_product()) {
$get_id = $post->ID;
$amp_location = get_post_meta($get_id, 'wc_mobile_version_url', true);
if ($amp_location) {
?>
<link rel="amphtml" href="<?php echo $amp_location; ?>"/>
<?php
}
}
}
add_action('wp_head', 'wc_49570125_amp_google_link');
I tested above code and seems it works well.