没有插件的电子商务的AMP版本



我有两个电子商务网站的产品页面:一个用woocommerce制造(在wordpress中(,一个我在amp中编码了自己的自我。

这是WordPress页面,这是AMP页面。不考虑这两个页面在两个不同的子域上,我将如何将移动用户重定向到页面的AMP版本?

提出了一个类似的问题,但它仅指定了如何在简单页面而不是产品页面上进行操作。

有人知道如何做吗?

要回答您的问题,如果您不想使用插件,则必须在主题function.php中使用以下几行。

按照您的问题使其正常工作

  1. 在WooCommerce的产品邮政类型中创建Metabox
  2. 将输入字段添加到创建的Metabox
  3. 通过save_post操作钩保存输入字段
  4. 输入每种产品的特定URL
  5. 从产品中获取保存的数据,如果是移动用户,则重定向。

步骤1:创建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');

步骤2:添加输入字段

// 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
}

步骤3:保存输入字段

// 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');

步骤4:将移动用户重定向到移动版本

// 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');

步骤5:添加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');

我测试了上面的代码,并且似乎运行良好。

最新更新