如何使用Wordpress基于设备设置主页?

时间:2018-10-10 16:43:31

标签: wordpress custom-wordpress-pages

我需要根据访问者设备(移动设备/台式机)设置默认主页,我在插件中尝试了以下代码,但没有用。

if ( wp_is_mobile() ) {
  $homepage = get_page_by_title( 'mobile' );
}else{
  $homepage = get_page_by_title( 'home1' );
}
if ( $homepage ){           
  update_option( 'page_on_front', $homepage->ID );      
  update_option( 'show_on_front', 'page' );                 
}

它会继续加载从主题选项中选择的home1。

谢谢

1 个答案:

答案 0 :(得分:0)

即使您的当前功能“起作用”,它也将无法使用。您正在尝试根据最新访问者的设备在数据库中设置网站范围的选项。

使用update_option()并不符合您的最大利益。您应该做的是使用template_include过滤器,根据用户设备以编程方式更改在运行时加载的模板-这样,您就不会在数据库中存储(半)永久更改,这会被任何用户不断覆盖无数次,并影响所有其他用户。

这最终看起来像这样:

add_filter( 'template_include', 'so_52745088_homepage_template', 99 );
function so_52745088_homepage_template( $template ){
    // Only execute on the front page, not pages/posts/cpts
    if( is_front_page() ){
        // Determine if mobile
        if( wp_is_mobile() ){
            // Make sure mobile homepage template is found
            if( $home_template = locate_template( array( 'homepage-mobile.php' ) ) ){
                return $new_template;
            }
        }
    }

    return $template;
}

如果您没有用于移动设备的单独页面模板,而只是一个普通的单独页面,那么您可以考虑在任意数量的挂钩上使用wp_safe_redirect(),常见的是{{3 }},最终看起来像这样:

add_action( 'template_redirect', 'so_52745088_homepage_redirect' );
function so_52745088_homepage_redirect( $template ){
    // Only execute on the front page, not pages/posts/cpts
    if( is_front_page() ){
        // Determine if mobile
        if( wp_is_mobile() ){
            wp_safe_redirect( 'mobile' );
            exit;
        }
    }
}