在 wordpress 中,我创建了 2 个自定义帖子类型:公司和报价 报价链接到具有名为公司名称的自定义字段的公司。
因此,如果名为“我的报价”的报价链接到公司“ACME”,则两个帖子类型都包含一个名为“公司名称”的自定义字段,其值为 ACME。到目前为止没有问题。
我用默认的 slug 'company' 和 'offer' 注册了两个自定义 posttype
商店永久链接网址现在是:www.mywebsite.nl/company/acme/ 优惠永久链接网址现在是:www.mywebsite.nl/offer/my-offer/
我想要的是将永久链接更改为 www.mywebsite.nl/company/acme/my-offer/
我通过过滤器/操作/ Hook (和 stackoverflow)进行了很多搜索,但找不到解决方案。我什至尝试使帖子类型分层,但在“报价”帖子类型中,我无法将“公司”帖子类型设置为父级。
如何获取我需要的url结构?
最佳答案
您需要解决两件事。
首先,您需要将要约的 url 更改为您的新表单。这是通过指定一个 slug 来完成的,您可以为每个优惠修改该 slug。
注册帖子类型时,给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
关于Wordpress 自定义帖子类型永久链接父/子但不同类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25890432/