【问题标题】:How to add a slash at the end of category's url and remove it at the end of post's on wordpress?如何在类别网址的末尾添加斜杠并在 wordpress 上的帖子末尾删除它?
【发布时间】:2019-01-17 16:26:34
【问题描述】:

如何使 wordpress 类别的 URL 在末尾带有斜杠,而在帖子的 url 中不带斜杠。像这样:

“mysite.com/mycategory/” “mysite.com/mycategory/mypost”

问题在于,默认情况下,您可以使用斜线来执行所有操作,也可以不使用斜线来执行所有操作。 (“类别”前缀已通过 htaccess 删除)。

【问题讨论】:

    标签: php wordpress url categories permalinks


    【解决方案1】:

    我是这样解决的:

    function no_page_slash( $string, $type ){
        if($type == 'single')
            $string = untrailingslashit($string);
       return $string;
    }
    add_filter('user_trailingslashit', 'no_page_slash', 70, 2);
    

    您的永久链接必须设置为 /%category%/%postname%/ 。

    【讨论】:

      【解决方案2】:

      有两个很好的解决方案:

      WP_Rewrite 类有一个名为 $use_trailing_slashes 的变量,它是根据您的自定义永久链接结构是否以“/”结尾而动态设置的。

      $this->use_trailing_slashes = ( '/' == substr($this->permalink_structure, -1, 1) );
      

      这意味着所有 WP 生成的链接(the_permalink、category_link、the_permalink_rss 等)都不会以“/”结尾。因此,对于类别页面,WP 将显示“/category/category”而不是“/category/category/”。

      您可以通过使用过滤器或修改您的 .htaccess 或两者来解决它:

      user_trailingslashit 过滤器示例

      user_trailingslashit 函数在返回结果之前将“user_trailingslashit”过滤器应用于结果。它为过滤器提供 url 和 url 的类型。

      $string = apply_filters('user_trailingslashit', $string, $type_of_url);
      

      因此,要挂钩并在除单个帖子之外的所有 URL 中添加尾部斜杠,请将此代码添加到插件文件或您的 functions.php 主题文件中。

      function fix_trailingsss($s='',$t='single')
      {
        if($t!='single')$s=rtrim($s,'/').'/';
        return preg_replace('/^(.*)([^l/])$/i', '\1\2/',$s);
      }
      add_filter('user_trailingslashit', 'fix_trailingsss', 9999,2);
      

      Htaccess 重定向匹配

      您可以设置 .htaccess 重定向以强制类别网址始终使用尾部斜杠,如下所示:

      RedirectMatch 301 ^/category/([^/]+)$ /category/$1/
      

      信息来源https://www.askapache.com/wordpress/adding-trailing-permalinks/

      如有任何其他问题,请查阅法典:

      https://codex.wordpress.org/wp_rewrite

      https://codex.wordpress.org/Using_Permalinks

      【讨论】:

        猜你喜欢
        • 2013-01-18
        • 2011-08-21
        • 1970-01-01
        • 2010-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-02
        • 1970-01-01
        相关资源
        最近更新 更多