发布于 2018-03-30 00:13:29
要回答您的问题,如果您不想使用插件,就必须在主题functions.php中硬编码以下几行代码。
根据你的问题,让它发挥作用的方法如下
步骤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');
我测试了上面的代码,看起来效果很好。
https://stackoverflow.com/questions/49570125
复制相似问题