WordPress多站点如何实现下拉按钮仅在指定URL页面显示
方案1:WordPress多站点原生PHP判断(最推荐)
直接利用WordPress多站点内置函数判断当前所属子站点,服务器端动态渲染按钮,不会有前端闪现问题,也支持自定义每个站点的按钮文案、跳转链接和显隐规则,修改主题的header.php文件即可:
<?php // 获取当前子站点的首页URL $current_site_url = get_home_url(); // 配置每个站点的按钮规则,不需要显示的站点不用加入配置数组 $site_btn_config = [ // 根站点(英文站)配置 'https://example.com/' => [ 'button_text' => 'Languages', 'link_list' => [ 'https://example.com/' => 'English', 'https://example.com/de/' => 'Deutsch', 'https://example.com/es/' => 'Español', 'https://example.com/fr/' => 'Français', 'https://example.com.cn/' => '中文' ] ], // 德语站配置 'https://example.com/de/' => [ 'button_text' => 'Sprache', 'link_list' => [ 'https://example.com/de/' => 'Deutsch', 'https://example.com/' => 'English', 'https://example.com.cn/' => '中文' ] ], // 中文站配置示例 'https://example.com.cn/' => [ 'button_text' => '选择语言', 'link_list' => [ 'https://example.com.cn/' => '中文', 'https://example.com/' => 'English', 'https://example.com/de/' => 'Deutsch' ] ] ]; // 仅当前站点在配置数组中时渲染按钮 if (isset($site_btn_config[$current_site_url])) : $current_config = $site_btn_config[$current_site_url]; ?> <div class="dropdown"> <button class="dropbtn"><?php echo esc_html($current_config['button_text']); ?></button> <div class="dropdown-content"> <?php foreach ($current_config['link_list'] as $link => $text) : ?> <a href="<?php echo esc_url($link); ?>"><?php echo esc_html($text); ?></a> <?php endforeach; ?> </div> </div> <?php endif; ?>
后续新增站点只需要在配置数组里加对应配置即可,不需要改逻辑代码。
方案2:CSS快速控制显隐(临时修改首选)
如果只需要控制按钮显隐,不需要改内容,WordPress多站点默认会在body标签上输出每个站点独有的ID类,格式为blog-id-数字,你可以在主题的自定义CSS面板添加以下代码:
/* 所有站点默认隐藏按钮 */ .dropdown { display: none; } /* 只给需要显示的站点放开显示权限,比如ID为1的根站点、ID为4的中文站 */ .blog-id-1 .dropdown, .blog-id-4 .dropdown { display: block; }
你可以在站点后台的多站点管理界面查看每个子站点对应的ID。
方案3:前端JS动态适配(只能改前端代码时使用)
如果没有权限修改主题PHP代码,可以在头部引入以下JS代码实现需求:
const currentPath = window.location.pathname.split('/')[1]; const dropdown = document.querySelector('.dropdown'); const dropbtn = document.querySelector('.dropbtn'); const linkWrap = document.querySelector('.dropdown-content'); // 配置需要显示按钮的路径规则,以及对应按钮内容 const btnRule = { // 根站点 '': { text: 'Languages', links: { 'https://example.com/': 'English', 'https://example.com/de/': 'Deutsch', 'https://example.com/es/': 'Español', 'https://example.com/fr/': 'Français', 'https://example.com.cn/': '中文' } }, // 中文站 'cn': { text: '选择语言', links: { 'https://example.com.cn/': '中文', 'https://example.com/': '英文', 'https://example.com/de/': '德文' } } } // 不在规则内的站点直接隐藏按钮 if (!btnRule.hasOwnProperty(currentPath)) { dropdown.style.display = 'none'; } else { // 动态替换按钮内容和跳转链接 const currentRule = btnRule[currentPath]; dropbtn.innerText = currentRule.text; let linkHtml = ''; Object.keys(currentRule.links).forEach(url => { linkHtml += `<a href="${url}">${currentRule.links[url]}</a>`; }) linkWrap.innerHTML = linkHtml; }
内容的提问来源于stack exchange,提问作者Kfietek
相关产品推荐
相关产品推荐

