rewrite rules - Custom permalink question

admin2025-06-02  1

I have a multisite environment where I am switching databases to retrieve data in a custom post type entered on one site to show on the other site.

On the site where the data is not stored (and the post type is not defined), I want a permalink like /post-type-name/item-slug/ to end up at a page named /post-type-name/. I can then write code in the page specific template to switch databases, retrieve the data for item-slug, and show it. But I am not sure how to make the permalink work, other than to do it like /post-type-name?item-slug.

I have a multisite environment where I am switching databases to retrieve data in a custom post type entered on one site to show on the other site.

On the site where the data is not stored (and the post type is not defined), I want a permalink like /post-type-name/item-slug/ to end up at a page named /post-type-name/. I can then write code in the page specific template to switch databases, retrieve the data for item-slug, and show it. But I am not sure how to make the permalink work, other than to do it like /post-type-name?item-slug.

Share Improve this question edited Feb 26, 2019 at 7:07 Krzysiek Dróżdż 25.6k9 gold badges53 silver badges74 bronze badges asked Feb 25, 2019 at 23:05 Barry TuberBarry Tuber 1 1
  • Ok, I looked around some more and was able to find a working solution here: rlmseo/blog/…. – Barry Tuber Commented Feb 26, 2019 at 0:21
Add a comment  | 

1 Answer 1

Reset to default 0

What you need is to register your own Rewrite Rule. To do it you should use add_rewrite_rule function.

function my_custom_external_rewrite_rule() {
    add_rewrite_rule('^post-type-name/([^/]+)/?', 'index.php?page_id=<PAGE_ID>&external_page_name=$matches[1]', 'top');
}
add_action( 'init', 'my_custom_external_rewrite_rule' );

And you'll have to register your custom query variable (using query_vars hook):

function my_custom_external_query_var( $query_vars ) {
    $query_vars[] = 'external_page_name';
    return $query_vars;
}
add_filter( 'query_vars', 'my_custom_external_query_var' );

This way requests to post-type-name/slug/ will cause displaying page with and you will be able to obtain the slug of external post with get_query_var( 'external_page_name' );

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748860264a314323.html

最新回复(0)