【问题标题】:Wordpress Custom Type permalink containing Taxonomy slug包含分类 slug 的 Wordpress 自定义类型永久链接
【发布时间】:2011-12-05 03:00:39
【问题描述】:

我正在尝试为自定义类型创建一个永久链接模式,其中包括其分类法之一。分类名称从一开始就是已知的(所以我不想添加或混合它的所有分类,只是一个特定的),但值当然是动态的。

通常,自定义类型永久链接是使用 rewrite 参数和 slug 参数构建的,但我不知道如何在其中添加动态变量。

http://codex.wordpress.org/Function_Reference/register_post_type

我猜测需要自定义解决方案,但我不确定最好的非侵入式方法是什么。

这方面是否有已知的做法,或者最近有人构建过类似的东西吗?我正在使用 WP 3.2.1 顺便说一句。

【问题讨论】:

    标签: wordpress taxonomy permalinks custom-type


    【解决方案1】:

    经过更多搜索后,我设法使用custom_post_link 过滤器创建了相当优雅的解决方案。

    假设您有一个 project 自定义类型和一个 client 分类。添加这个钩子:

    function custom_post_link($post_link, $id = 0)
    {
      $post = get_post($id);
    
      if(!is_object($post) || $post->post_type != 'project')
      {
        return $post_link;
      }
      $client = 'misc';
    
      if($terms = wp_get_object_terms($post->ID, 'client'))
      {
        $client = $terms[0]->slug;
    
        //Replace the query var surrounded by % with the slug of 
        //the first taxonomy it belongs to.
        return str_replace('%client%', $client, $post_link);
      }
    
      //If all else fails, just return the $post_link.
      return $post_link;
    }
    
    add_filter('post_type_link', 'custom_post_link', 1, 3);
    

    然后,在注册自定义类型时,像这样设置rewrite arg:

    'rewrite' => array('slug' => '%client%')
    

    我想我应该在问之前深入挖掘,但至少我们现在有了一个完整的解决方案。

    【讨论】:

    • 谢谢!这对我有用。我必须确保我的.htaccess 文件是可写的,然后进入Settings > Permalinks'Save Changes' 才能正常工作。 add_filter('post_type_link', 'custom_post_link', 1, 3); 中的 13 是什么?再次感谢!
    • 我以为我一切正常,但现在我在所有常规/非自定义帖子类型的帖子上都收到 404 错误。如果您对此有任何想法,我已经发布了一个问题:stackoverflow.com/questions/9722984/…
    • 强烈建议使用 'get_the_terms' 而不是 'wp_get_object_terms' 因为 'get_the_terms' 会缓存结果。使用“wp_get_object_terms”将导致每次运行“post_link”过滤器时都会运行该查询,这就像在“编辑帖子”屏幕上运行 10 次。参考core.trac.wordpress.org/browser/tags/3.9.1/src/wp-includes/…
    猜你喜欢
    • 2014-08-28
    • 2013-04-18
    • 2012-05-05
    • 1970-01-01
    • 1970-01-01
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    相关资源
    最近更新 更多