You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress PHP按屏幕宽度查询数据:仅移动端条件生效问题排查

问题原因分析

你当前的代码逻辑存在核心错误:PHP是服务器端执行语言,JavaScript是客户端执行语言,你把JS代码字符串直接赋值给PHP变量$width,PHP运行时这个变量的值是字符串<script>document.write(screen.width);</script>,而非实际的屏幕宽度数值。

当PHP执行字符串与数字的比较时,会将字符串强制转换为数字,这里转换结果是0,所以0 <= 720永远成立,桌面端的判断条件永远不会触发。


解决方案

方案1:前端渲染判断(适合数据量小的场景)

先在后端一次性获取移动端和桌面端的所有数据,再通过前端JS判断屏幕宽度,渲染对应内容。

<?php
$table_header_name = 'header'; // Table Name

// 同时拉取移动端、桌面端数据
$mobile_rows = $wpdb->get_results( 
    "SELECT * FROM $table_header_name WHERE play_mode = 1 AND device_mode = 1 ORDER BY rank_mode ASC", 
    ARRAY_A 
);
$desktop_rows = $wpdb->get_results( 
    "SELECT * FROM $table_header_name WHERE play_mode = 1 AND device_mode = 0 ORDER BY rank_mode ASC", 
    ARRAY_A 
);

// 转成JSON格式供前端调用
$mobile_json = json_encode($mobile_rows);
$desktop_json = json_encode($desktop_rows);
?>

<!-- 渲染容器 -->
<div class="widget-header-content"></div>

<script>
const container = document.querySelector('.widget-header-content');

// 渲染内容的通用方法
function renderItems(data) {
    let html = '';
    data.forEach(item => {
        // 这里根据你的数据结构拼接HTML,示例用item.title作为展示字段
        html += `<div class="header-item">${item.title}</div>`;
    });
    container.innerHTML = html;
}

// 初始渲染
const initialWidth = screen.width;
if (initialWidth <= 720) {
    renderItems(<?php echo $mobile_json; ?>);
} else {
    renderItems(<?php echo $desktop_json; ?>);
}

// 监听窗口尺寸变化,实时切换内容(加防抖避免频繁触发)
let resizeTimer;
window.addEventListener('resize', () => {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(() => {
        const newWidth = screen.width;
        if (newWidth <= 720) {
            renderItems(<?php echo $mobile_json; ?>);
        } else {
            renderItems(<?php echo $desktop_json; ?>);
        }
    }, 200);
});
</script>

方案2:AJAX动态请求(适合数据量大的场景)

通过前端JS获取屏幕宽度后,异步请求后端接口拉取对应设备的数据,减少初始加载的数据量。

第一步:在插件中注册AJAX接口

// 注册AJAX动作,支持登录/未登录用户访问
add_action('wp_ajax_get_header_data', 'get_header_data_callback');
add_action('wp_ajax_nopriv_get_header_data', 'get_header_data_callback');

function get_header_data_callback() {
    global $wpdb;
    $table_header_name = 'header';
    
    // 获取前端传来的设备类型参数(1=移动端,0=桌面端)
    $device_mode = isset($_GET['device_mode']) ? intval($_GET['device_mode']) : 1;
    
    // 查询对应数据
    $rows = $wpdb->get_results( 
        "SELECT * FROM $table_header_name WHERE play_mode = 1 AND device_mode = $device_mode ORDER BY rank_mode ASC", 
        ARRAY_A 
    );
    
    // 返回JSON格式结果
    wp_send_json_success($rows);
    wp_die();
}

第二步:小工具前端代码

<!-- 渲染容器 -->
<div class="widget-header-content"></div>

<script>
const container = document.querySelector('.widget-header-content');

// 根据屏幕宽度判断设备类型
function getDeviceMode() {
    return screen.width <= 720 ? 1 : 0;
}

// 请求并渲染数据
function loadHeaderData() {
    const deviceMode = getDeviceMode();
    fetch(`<?php echo admin_url('admin-ajax.php'); ?>?action=get_header_data&device_mode=${deviceMode}`)
        .then(res => res.json())
        .then(result => {
            if (result.success) {
                let html = '';
                result.data.forEach(item => {
                    html += `<div class="header-item">${item.title}</div>`;
                });
                container.innerHTML = html;
            }
        });
}

// 初始加载
loadHeaderData();

// 窗口尺寸变化时重新加载(加防抖)
let resizeTimer;
window.addEventListener('resize', () => {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(loadHeaderData, 200);
});
</script>

内容的提问来源于stack exchange,提问作者Crazy Hamster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 00:06:24