-
Notifications
You must be signed in to change notification settings - Fork 0
Theming content from within a plugin
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.
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.
// 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' );
}
Filter WordPress page content variables by using hooks to replace the default content with output from your plugin:
- Page title: the_title()
- Page content: the_content()
Note: you must complete all content filtering prior to calling get_header()
or some core stylesheets may not load properly.
/**
* 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' );
}