Load page template with custom content using a plugin

I want to load the page.php template with the content I specify (using variables and not from the database) if the request contains a particular query string.

So lets say a user requests example.com/?var1=str1 the page template should be displayed with the title and content I specify using variables.

This is the pseudo code of what I’m trying to achieve

<?php
function my_page_function() {
if($_REQUEST['var1'] == "str1")
{
$title="This will be the title of the default page template";
$content="This content will be displayed on the default page template.";
//Load the page.php here with the title and content specified in the variables above
}
}
add_action("template_redirect","my_page_function");
?>

I wish to use this code in a plugin, so it should work with any theme’s page.php.

2 Answers
2

You can achieve that with filters on the_content and the_title:

function wpa_content_filter( $content ) {
    if( isset( $_REQUEST['var1'] ) && $_REQUEST['var1'] == "str1" ) {
        return 'This content will be displayed on the default page template.';
    }
    return $content;
}
add_filter( 'the_content', 'wpa_content_filter', 999 );

Leave a Comment