0

Hoping you can help with this...

WE have a 'serivces' custom post type that allows a 'service' to have a parent 'service'. Our custom rewrite rule works for top-level services but not child services.

The url structure would be something like the following where 'test-service' and 'test-service-child' are the post names:

  1. consultancy/test-service
  2. consultancy/test-service/test-service-child

Our existing rewrite rule is as follows:

add_rewrite_rule('^consultancy/(.*)/?', 'index.php?post_type=service&name=$matches[1]', 'top');

Can anyone suggest a modification that will get the post name from the end of the url? Eg in the case of the examples above it should match the following

  1. test-service
  2. test-service-child

Any help greatly appreciated. Thanks in advance,

Will

0

Our custom rewrite rule works for top-level services but not child services.

Your rewrite rule, or the query (the second parameter for add_rewrite_rule()) is just missing a service query:

add_rewrite_rule( // wrapped for brevity
    '^consultancy/(.*)/?',

    // Here, add the &service=$matches[1]
    'index.php?post_type=service&name=$matches[1]&service=$matches[1]',

    'top'
);

But, why don't you just use consultancy as the rewrite slug when you register the post type?

register_post_type( 'service', [
    'public'       => true,
    'rewrite'      => [ 'slug' => 'consultancy' ],
    'hierarchical' => true,
    // .. other args here.
] );

That way, you wouldn't need the custom rewrite rule because the above 'slug' => 'consultancy' will set the permalink structure for your "service" posts to consultancy/<post name/slug>.

Can anyone suggest a modification that will get the post name from the end of the URL?

You can use:

  • get_query_var( 'service' ) or get_query_var( 'name' ) to get the complete post name/slug path from the current URL.

    So if the URL is https://example.com/consultancy/test-service/test-service-child, you'd get test-service/test-service-child.

  • get_queried_object()->post_name to get the actual post name/slug for the queried post, i.e. without the parent path.

    So if the URL is https://example.com/consultancy/test-service/test-service-child, get_queried_object()->post_name would return test-service-child (note the child).

1
  • 1
    That's wonderful, works perfectly. Thank you. In answer to your question re using Consultancy as the slug - that bit is actually dynamic as each service falls under one of a list of Sectors so we're having to do this: $service_sectors = indigo_get_service_sectors(); foreach ($service_sectors as $key => $value) { add_rewrite_rule('^'.$key.'/(.*)/?', 'index.php?post_type=service&name=$matches[1]&service=$matches[1]', 'top'); } Jun 18 '20 at 15:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.