Skip to content

Theming content from within a plugin

Jason Chafin edited this page Jun 15, 2022 · 3 revisions

This document assumes you need to render a themed web page using your plugin. If you are working on a .php based plugin, the following should be built into the plugin in order to render a themed page.

UC Santa Cruz has created a starter plugin based on these instructions that can be forked and used as the base code for plugin development.

Call proper theme template files

There are three template files in the theme that plugins should include:

  • header-plugin.php
  • content-plugin.php
  • footer-plugin.php

The header-plugin.php and footer-plugin.php files should be included using WordPress' get_header() and get_footer() callbacks.

The content-plugin.php should be included using WordPress' get_template_part() callback.

Example

// Call Header
if ( file_exists( get_theme_file_path( 'header-plugin.php' ) ) ) {
 get_header( 'plugin' );
}

// Call Content template. 
// Content in this template will be filtered by plugin content
if ( file_exists( get_theme_file_path( 'content-plugin.php' ) ) ) {
 get_template_part( 'content', 'plugin' );
}

// Call Footer
if ( file_exists( get_theme_file_path( 'footer-plugin.php' ) ) ) {
 get_footer( 'plugin' );
}

Add plugin page output by filtering WordPress content variables

Filter WordPress page content variables by using hooks to replace the default content with output from your plugin:

Note: you must complete all content filtering prior to calling get_header() or some core stylesheets may not load properly.

Example

/**
 * Plugin Name: UCSC Plugin
 * @package ucsc-plugin
 */

//
// Your plugin logic and processing
// output into 1-2 variables:
//
// $page_title = The title of your page
// $page_content = The content you want to appear on the page
//


// Filter 'the_title' WordPress variable for use in 'content-plugin.php'
add_filter('the_title', $page_title);

// Filter 'the_content' WordPress variable for use in 'content-plugin.php'
add_filter('the_content', $page_content);

// Call header
if ( file_exists( get_theme_file_path( 'header-plugin.php' ) ) ) {
 get_header( 'plugin' );
}

// Call content using get_template_part()
if ( file_exists( get_theme_file_path( 'content-plugin.php' ) ) ) {
 get_template_part( 'content', 'plugin' );
}

// Call footer
if ( file_exists( get_theme_file_path( 'footer-plugin.php' ) ) ) {
 get_footer( 'plugin' );
}