在WordPress页面上命名为锚的漂亮URL



我在一个WordPress网站上工作,其中服务页面是一个长页,每个部分都有锚。

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

.htaccess文件中是否有任何方法可以制作一个URL,例如www.mysite.com/services/human-resources/直接跳到锚点?

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

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

,但这表明URL中的#破坏了目的。删除R=301只是使它无所作为。

谢谢。

我一直在一个类似的网站上工作,这就是我解决这个问题的方式。

首先将此操作添加到functions.php,Witch将用户重定向到页面上的适当锚。

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 */

希望这有帮助

最新更新