In other common PHP frameworks you normally propagate a new route and have a controller as callback print the desired output. In WordPress something like that doesn’t seem to be built in – at the moment.
But what I’d recommend is to somehow mimic this approach.
- In a custom plugin have a rule that when a certain custom URL is being called a certain custom template will be used to render the main content.
- In that plugin provide a function (or multiple functions) that takes care of the business logic and prepares the desired output.
- Inside the certain custom template from the first step call that function.
For example.
<?php
/*
Plugin Name: My Plugin
Description: Lorem ipsum dolor sit amet.
Version: 1.0
Author: You
Author URI: https://example.com
*/
class MyPlugin {
public function __construct() {
add_action('template_include', [$this, 'template_suggestion'];
}
function template_suggestion($template) {
global $wp;
$current_slug = $wp->request;
$custom_template = locate_template(['foobar.php']);
if ($current_slug == 'lorem-ipsum' && $custom_template != '') {
status_header(200);
return $custom_template;
}
return $template;
}
public static function Foo() {
// Do whatever you need to do to build your markup.
$output="<div>";
$output .= 'Foo';
$output .= '</div>';
return $output;
}
public static function Bar() {
// Do whatever you need to do to build your markup.
$output="<div>";
$output .= 'Bar';
$output .= '</div>';
return $output;
}
}
new MyPlugin();
And then inside foobar.php
simply:
<div>
<?php echo MyPlugin::Foo();?>
<?php echo MyPlugin::Bar();?>
</div>