0

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.

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' );

  • Thanks, the other solution I found omitted the step to register the query variable, so this was helpful. I had to change the $qvars variable to $query_vars in the code, otherwise all existing query variables were wiped out, which produced some interesting results... – Barry Tuber Feb 27 at 12:38
  • @BarryTuber ha, nice catch ;) I was answering on mobile, so it was easy to overlook that typo. I've fixed that already. – Krzysiek Dróżdż Feb 27 at 12:42

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.