WordPress custom post type permalink parent/child but different types

In wordpress I created 2 custom post types: company and offer
offers are linked to companies with a customfield called companyname.

So if an offer called ‘My offer’ is linked to Company ‘ACME’, both posttype contain a customfield called ‘companyname’ with value of ACME.So far no problem.

Read More

I registered both custom posttypes with a default slug ‘company’ and ‘offer’

The shop permalink url is now: www.mywebsite.nl/company/acme/
The offer permalink url is now: www.mywebsite.nl/offer/my-offer/

What I want is the offer permalink is changed to www.mywebsite.nl/company/acme/my-offer/

I searched a lot through filters/action/hooks (and stackoverflow), but I cannot find a solution. I even tried to make the post-types hierarchical, but in an ‘offer’ posttype I cannot make a ‘company’ posttype the parent.

How can get the url structure I need?

Related posts

Leave a Reply

1 comment

  1. There’s two things you need to solve.

    First, you need the url for the offers to be changed to your new form. This is done by specifying a slug that you can modify for each of the offers.

    When registering the post type, add a variable to the 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;
        }
    

    Second, you want wordpress to redirect incoming url requests to this post. Do this by adding a rewrite rule on the init action:

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

    Here are two articles with more info:

    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