Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to override a WordPress template with a plugin?

Tags:

wordpress

I'd like to make a landing page. If plugin detects some GET or POST requests it should override wordpress theme and show its own.

It would work somehow like that:

if (isset($_GET['action']) && $_GET['action'] == 'myPluginAction'){
    /* do something to maintain action */
    /* forbid template to display and show plugin's landing page*/
}

I'm familiar with WP Codex, but I don't remember if there is any function to do that. Of course, I googled it with no results.

Thanks for any ideas in advance.

like image 267
sznowicki Avatar asked Dec 21 '12 22:12

sznowicki


1 Answers

You need the hook template_include. It doesn't seem documented in the Codex, but you can find more examples here in SO or in WordPress StackExchange

Plugin file

<?php
/**
 * Plugin Name: Landing Page Custom Template
 */
add_filter( 'template_include', 'so_13997743_custom_template' );

function so_13997743_custom_template( $template )
{
    if( isset( $_GET['mod']) && 'yes' == $_GET['mod'] )
        $template = plugin_dir_path( __FILE__ ) . 'my-custom-page.php';

    return $template;
}

Custom Template in Plugin folder

<?php
/**
 * Custom Plugin Template
 * File: my-custom-page.php
 *
 */

echo get_bloginfo('name');

Result

Visiting any url of the site with ?mod=yes will render the plugin template file, e.g.: http://example.com/hello-world/?mod=yes.

like image 62
brasofilo Avatar answered Oct 15 '22 10:10

brasofilo