【问题标题】:Pretty URLs for named anchors on WordPress pageWordPress 页面上命名锚点的漂亮 URL
【发布时间】:2017-05-30 17:59:30
【问题描述】:

我正在开发一个 WordPress 网站,其中服务页面是一个长页面,每个部分都有锚。

www.mysite.com/services/#human-resources 按预期跳转到人力资源部分。

.htaccess文件中有没有办法让www.mysite.com/services/human-resources/等url直接跳转到锚点?

我尝试了几种不同的重写规则,我得到的最接近的是:

RewriteRule services/human-resources services/#human-resources [NE,L,R=301]

但这显示了 url 中的 # ,这违背了目的。删除 R=301 只会导致它什么也不做。

谢谢。

【问题讨论】:

    标签: wordpress .htaccess mod-rewrite


    【解决方案1】:

    我一直在研究一个类似的网站,这就是我解决这个问题的方法。

    首先将此动作添加到functions.php,将用户重定向到页面上的正确锚点。

    function url_handler(){
      $path = substr($_SERVER['REQUEST_URI'], 1); //get the path minus the '/'
      if( is_page() || is_404() ){ // do you own conditional tags
        wp_redirect( home_url("#" . $path) ); //redirect to the #anchor
        exit();
      }
    }
    add_action( 'template_redirect', 'url_handler' );
    

    接下来,您需要创建一个 javascirpt 处理程序来获取页面的 url(带有锚点的 url)并进行适当的事件以滚动到该部分。像这样的:

    var hash = window.location.hash;
    hash = hash.replace('#','');
    hash = hash.replace('/','');
    /* do stuff here */
    

    希望对你有帮助

    【讨论】:

      最近更新 更多