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.

Read More

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.

Related posts

2 comments

  1. 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 );
    
  2. Create the template file within your Plugin, e.g. template-pluginname.php, then hook into template_include and tell WordPress to use it:

    function wpse114181_template_include( $template ) {
        return ( '' != get_query_var( 'plugin_key' ) ? plugin_dir_path( __FILE__ ) . 'template-plugin.php' : $template );
    }
    add_filter( 'template_include', 'wpse114181_template_include' );
    

    Note: this requires that you register your query variable using add_query_arg(), but is safer than relying on $_REQUEST directly.

    Edit

    Based on this comment:

    The only problem with this code is that as I said earlier I want to plugin to work properly with any theme. So if I design a template file myself it wouldn’t look like the currently activated theme’s page.php

    If you are absolutely intent on overriding the Post Title and Post Content, then you can use the the_title and the_content filters:

    function wpse114181_filter_the_title( $title ) {
        if ( is_page() && '' != get_query_var( 'plugin_key' ) ) {
            return 'Your Post Title Here';
        } else {
            return $title;
        }
    }
    add_filter( 'the_title', 'wpse114181_filter_the_title' );
    
    function wpse114181_filter_the_content( $content ) {
        if ( is_page() && '' != get_query_var( 'plugin_key' ) ) {
            return 'Your Post Content Here';
        } else {
            return $content;
        }
    }
    add_filter( 'the_content', 'wpse114181_filter_the_content' );
    

Comments are closed.