【问题标题】:Remove sub category slug from permalink URL of blog post and custom post type in WordPress从博客文章的永久链接 URL 和 WordPress 中的自定义文章类型中删除子类别 slug
【发布时间】:2014-08-27 16:15:30
【问题描述】:

我的网站上使用了标准帖子和自定义帖子。基本上,对于标准和自定义帖子,我们需要以下内容。

父帖子类别,例如:“博客” 然后子类别到这个父类别。例如:

博客(父类别)

新闻(子类别)

LatestNewsPostOne

事件(子类别)

LatestEvnntssPostOne

因此帖子可以存在于任何或所有这些类别中。如果您访问“博客”类别,您将拥有以下永久结构:

domain.com/blog

如果您访问“新闻”类别,您将拥有以下永久结构:

domain.com/blog/news

但是,当您访问“LatestNewsPostOne”时,您将拥有以下永久结构:

domain.com/blog/LatestNewsPostOne

因此,在最后一个示例中,您会注意到,一旦您单击单个帖子将其打开。子类别从 url 中消失。目前我的网站留在了我不想要的子类别中。

有人知道在 WordPress 网站上实现此功能的任何解决方案吗?

【问题讨论】:

    标签: wordpress .htaccess permalinks


    【解决方案1】:

    我想通了。下面是我从博客文章永久链接 URL 中删除子类别 slug 的代码,我在主题文件夹中的 functions.php 文件中添加了以下内容:

    add_filter(
    'post_link',
    'custom_post_type_link',
    10,
    3); function custom_post_type_link($permalink, $post, $leavename) {
    if (!gettype($post) == 'post') {
        return $permalink;
    }
    switch ($post->post_type) {
        case 'post':
            //$permalink = get_home_url() . '/' . $post->post_name . '/';
    
            $cats = get_the_category($post->ID);
            $subcats = array();
            foreach( $cats as $cat ) {
                $cat = get_category($cat->term_id);
                if($cat->parent) { $subcats[] = sanitize_title($cat->name); }
            }
            if($subcats) {
                foreach($subcats as $subcat) {
                    $subcat = $subcat.'/';
                    $permalink = str_replace($subcat, "", $permalink);
                }
            }
    
    
            break;
    }
    
    return $permalink;}
    

    【讨论】:

      猜你喜欢
      • 2020-03-16
      • 2017-10-02
      • 2014-07-15
      • 1970-01-01
      • 2015-04-04
      • 2011-12-05
      • 2014-08-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多