0

I'd like to expose a route to my site, animals.example.com/book, that shows all content of pages and descendants specified in a query parameter.

For example, if my page structure is

intro
pets
    dogs
    cats
farm-animals
    cows
    chickens
    sheep
wild-animals
    predators
        wolves
        coyotes
    ruminants
        deer
        rabbits
appendix
    average-weights
    faq
    common-myths

I would like the endpoint

animals.example.com/book?include=[farm-animals,predators]

to render, in order, the content of these pages:

  • farm-animals
  • cows
  • chickens
  • sheep
  • predators
  • wolves
  • coyotes

If the query parameter is omitted, the entire site should be rendered.

What functions or queries are required to accomplish this, and where should this logic hook into WordPress?

2

You can add custom query variables to WordPress with add_query_var().

global $wp;
$wp->add_query_var( 'includes' );

Having added the query var you would check if it is passed with get_query_var('includes'), then you could use WP_Query() to get the pages (You can see the available args here).

If it's omitted you would simply run a query to get all children of the page.

Another nice addition would be to add the query var to the permalinks using add_rewrite_rules.

function custom_query_var() {
    global $wp;
    add_rewrite_rule( '^books/(.+)', 'index.php?pagename=books&includes=$matches[1], 'top' );
}
add_action( 'init', 'custom_query_var' );

You would need to flush these rules if you switch to a different theme.

function flush_custom_query_var() {
    flush_rewrite_rules();
}
add_action( 'after_theme_switch', 'flush_custom_query_var' );

I haven't actually tested the rewrite rules when passing an array of parameters instead of just a single one, so it would need some alteration.

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.