【问题标题】:Wordpress custom post type permalink parent/child but different typesWordpress 自定义帖子类型永久链接父/子,但类型不同
【发布时间】:2014-11-11 11:33:31
【问题描述】:

在 wordpress 中,我创建了 2 种自定义帖子类型:公司和报价 优惠与具有名为 companyname 的自定义字段的公司相关联。

因此,如果一个名为“我的报价”的报价链接到公司“ACME”,则两种 posttype 都包含一个名为“companyname”的自定义字段,其值为 ACME。到目前为止没有问题。

我使用默认 slug 'company' 和 'offer' 注册了两个自定义 posttype

商店永久链接网址现在是:www.mywebsite.nl/company/acme/ 优惠永久链接网址现在是:www.mywebsite.nl/offer/my-offer/

我想要的是优惠永久链接更改为 www.mywebsite.nl/company/acme/my-offer/

我通过过滤器/操作/钩子(和 stackoverflow)搜索了很多,但我找不到解决方案。我什至尝试让帖子类型分层,但在“报价”帖子类型中,我无法将“公司”帖子类型设为父级。

怎样才能得到我需要的url结构?

【问题讨论】:

    标签: wordpress rewrite permalinks


    【解决方案1】:

    你需要解决两件事。

    首先,您需要将要约的网址更改为新表单。这是通过指定一个可以为每个报价修改的 slug 来完成的。

    注册post类型的时候,给slug添加一个变量:

        // add modified 
        register_post_type('company_offer_type',array(
        ...
           'rewrite' => array(
                'slug' => 'company/%company%'
            ),
        ));
    
        // filter to rewrite slug
        add_filter( 'post_type_link', 'postTypeLink', 10, 2);
        function postTypeLink($link, $post)
        {
            if (get_post_type($post) === 'company_offer_type') {
                $company = // get company from $post
                $link = str_replace('%company%', $company, $link);
            }
            return $link;
        }
    

    其次,您希望 wordpress 将传入的 url 请求重定向到此帖子。通过在 init 操作上添加重写规则来做到这一点:

        // add rewrite rule for custom type
        add_rewrite_rule(
            'company/(.*)/(.*)',
            'index.php?post_type=company_offer_type&name=$matches[2]',
            'top'
        );
    

    这里有两篇提供更多信息的文章:

    http://code.tutsplus.com/articles/the-rewrite-api-the-basics--wp-25474

    http://code.tutsplus.com/articles/the-rewrite-api-post-types-taxonomies--wp-25488

    【讨论】:

    • 感谢您的建议。我会试试这个。但是我不认为它会起作用。我尝试了类似的东西。我注意到蛞蝓中的斜线被删除了。所以 'slug' => 'company/%company%' 在之前的测试中变成了 'slug' => 'company-%company%'。
    猜你喜欢
    • 2013-01-28
    • 1970-01-01
    • 1970-01-01
    • 2018-07-03
    • 2021-06-10
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    相关资源
    最近更新 更多