WordPress how to create templates and url in custom plugin - wordpress

I know how to create a single page and archive page but now I am trying to move everything into a custom plugin. So far I created my custom post type, 'location' and I created my files
/templates/archive-location.php
/templates/single-location.php
How can I get mysite.com/locations to read my archive-location.php all within my custom plugin.
***Update****
I was able to get my single page to work. Now how do I make it so this can be included in any site? For instance I don't know their layout, should I include header and footer?
I need it so if I remove my plugin, mysite.com/locations doesn't exist anymore.

Here is a code for dynamically create custom templates during custom plugin is activated.
suppose i want to create two page first and second and i would like to assign custom templates to it.
Put below the code in your custom plugin's main file like index file of your custom plugin.
/* Runs when plugin is activated */
register_activation_hook(__FILE__,'news_plugin_install');
/* Runs on plugin deactivation*/
register_deactivation_hook( __FILE__, 'news_plugin_remove' );
function news_plugin_install() {
$newsGagPages = array(
'First Page',
'Second Page'
);
foreach ($newsGagPages as $postTitle) {
$my_post = array(
'post_title' =>$postTitle,
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'page',
'post_status'=>'publish');
if(!get_page_by_title($postTitle))
{
$pageID = wp_insert_post($my_post,true);
}
if($postTitle =="First Page" ){
add_post_meta( $pageID, '_wp_page_template', 'template-first.php' );
}
if($postTitle =="Second Page" ){
add_post_meta( $pageID, '_wp_page_template', 'template-second.php' );
}
}
}
class PageTemplater {
/* A Unique Identifier */
protected $plugin_slug;
/**
* A reference to an instance of this class.
*/
private static $instance;
/**
* The array of templates that this plugin tracks.
*/
protected $templates;
/**
* Returns an instance of this class.
*/
public static function get_instance() {
if( null == self::$instance ) {
self::$instance = new PageTemplater();
}
return self::$instance;
}
/**
* Initializes the plugin by setting filters and administration functions.
*/
private function __construct() {
$this->templates = array();
// Add a filter to the attributes metabox to inject template into the cache.
add_filter('page_attributes_dropdown_pages_args',array( $this, 'register_project_templates' )
);
// Add a filter to the save post to inject out template into the page cache
add_filter('wp_insert_post_data',array( $this, 'register_project_templates' )
);
// Add a filter to the template include to determine if the page has our
// template assigned and return it's path
add_filter('template_include',array( $this, 'view_project_template')
);
// Add your templates to this array.
$this->templates = array(
'template-first.php' => 'First',
'template-second'=>'Second ',
);
}
/**
* Adds our template to the pages cache in order to trick WordPress
* into thinking the template file exists where it doens't really exist.
*
*/
public function register_project_templates( $atts ) {
// Create the key used for the themes cache
$cache_key = 'page_templates-' . md5( get_theme_root() . '/' . get_stylesheet() );
// Retrieve the cache list.
// If it doesn't exist, or it's empty prepare an array
$templates = wp_get_theme()->get_page_templates();
if ( empty( $templates ) ) {
$templates = array();
}
// New cache, therefore remove the old one
wp_cache_delete( $cache_key , 'themes');
// Now add our template to the list of templates by merging our templates
// with the existing templates array from the cache.
$templates = array_merge( $templates, $this->templates );
// Add the modified cache to allow WordPress to pick it up for listing
// available templates
wp_cache_add( $cache_key, $templates, 'themes', 1800 );
return $atts;
}
/**
* Checks if the template is assigned to the page
*/
public function view_project_template( $template ) {
global $post;
if (!isset($this->templates[get_post_meta($post->ID, '_wp_page_template', true)] ) ) {
return $template;
}
$file = plugin_dir_path(__FILE__). get_post_meta($post->ID, '_wp_page_template', true);
// Just to be safe, we check if the file exist first
if( file_exists( $file ) ) {
return $file;
}else {
echo $file;
}
return $template;
}
}
add_action( 'plugins_loaded', array( 'PageTemplater', 'get_instance' ) );

Related

How do I access vc_map() internal values to create custom markup for WPBakery interface?

A similar question has been asked here, without any viable responses: Visual Composer custom markup for custom shortcode (vc_map)
and here: Visual Composer custom shortcode template - custom_markup display user input
I am trying to create custom markup within the WPBakery interface.
I can add custom markup no problem by doing:
$markup = 'test';
vc_map( array(
"name" => __("MyShortcode"),
"base" => "myshortcode",
"category" => __('Content'),
"custom_markup" => $markup, // #TODO how do we access shortcode's attributes here to display in bakery grid
"params" => $params
) );
This will output "test" in the WPBakery grid which is good, but how do I access vc_map() internal values to display?
For instance I have "post types" as a field for this shortcode. If someone selects "page" post type for example, I would like to display those posts within the WPBakery grid. What I cannot figure out is how to get the values that the user selected to display.
Any help would be greatly appreciated. I've searched endlessly on this one.
I found a solution. By extending the class WPBakeryShortCode, you could change the contentAdmin output :
// Extend Class WPBakeryShortCodesContainer
if (class_exists('WPBakeryShortCode')) {
class WPBakeryShortCode_Custom_Element extends WPBakeryShortCode {
/**
* #param $atts
* #param $content
*
* #return string
* #throws \Exception
*/
public function contentAdmin( $atts, $content = null ) {
$output = $custom_markup = $width = $el_position = '';
if ( null !== $content ) {
$content = wpautop( stripslashes( $content ) );
}
$shortcode_attributes = array( 'width' => '1/1' );
$atts = vc_map_get_attributes( $this->getShortcode(), $atts ) + $shortcode_attributes;
$this->atts = $atts;
$elem = $this->getElementHolder( $width );
if ( isset( $this->settings['custom_markup'] ) && '' !== $this->settings['custom_markup'] ) {
$markup = $this->settings['custom_markup'];
$elem = str_ireplace( '%wpb_element_content%', $this->customMarkup( $markup, $content ), $elem );
$output .= $elem;
} else {
$inner = $this->outputTitle( $this->settings['name'] );
$inner .= $this->paramsHtmlHolders( $atts );
$elem = str_ireplace( '%wpb_element_content%', $inner, $elem );
$output .= $elem;
}
return $output;
}
}
}
I follow this Git example to create my custom elements : https://gist.github.com/Webcreations907/ff0b068c5c364f63e45d

how to get wp_editor to save data in plugin admin page

I'm trying to use plugin settings api to add wp_editor, but the text/html is not saving.
// add the admin settings and such
add_action('admin_init', 'wp_myplugin_admin_init');
function wp_myplugin_admin_init(){
register_setting( 'wp_myplugin_settings', 'wp_myplugin_settings', 'wp_myplugin_settings_validate');
add_settings_field('wp_myplugin_user_custom_text', __('Enter your message','WP-wp_myplugin'), 'wp_myplugin_user_custom_text', 'wp_myplugin', 'wp_myplugin_main');
function wp_myplugin_user_custom_text() {
$options = get_option('wp_myplugin_settings');
$settings = array('textarea_rows' => 5,'textarea_name' => 'user_cutom _text_msg');
wp_editor( $options['user_custom_text'],'user_custom_text', $settings );}
// validate
function wp_myplugin_settings_validate() {
$options = get_option('wp_myplugin_settings');
$user_custom_text = $input['user_custom_text'];
if ( empty($user_custom_text) ){
$options['user_custom_text'] = $user_custom_text;
}else{
$options['user_custom_text'] = __('Enter your own text','WP-wp_myplugin');// as set when the plugin activated
I used the $input['user_custom_text'];
all I needed was $_POST['user_custom_text'];
also to get the media to work need wordpress Sanitize:
<?php wp_kses_post( $data ); ?>
http://codex.wordpress.org/Function_Reference/wp_kses_post
Incase there are anyone who followed the steps on the Creating Options Page on the Wordpress Codex and finding a hard time saving their input, you can use the below code to make sure the wp_editor saves your input.
<?php
class MySettingsPage
{
/**
* Holds the values to be used in the fields callbacks
*/
private $options;
/**
* Start up
*/
public function __construct()
{
add_action( 'admin_menu', array( $this, 'add_plugin_page' ) );
add_action( 'admin_init', array( $this, 'page_init' ) );
}
/**
* Add options page
*/
public function add_plugin_page()
{
// This page will be under "Settings"
add_options_page(
'Settings Admin',
'My Settings',
'manage_options',
'my-setting-admin',
array( $this, 'create_admin_page' )
);
}
/**
* Options page callback
*/
public function create_admin_page()
{
// Set class property
$this->options = get_option( 'my_option_name' );
?>
<div class="wrap">
<h1>My Settings</h1>
<form method="post" action="options.php">
<?php
// This prints out all hidden setting fields
settings_fields( 'my_option_group' );
do_settings_sections( 'my-setting-admin' );
submit_button();
?>
</form>
</div>
<?php
}
/**
* Register and add settings
*/
public function page_init()
{
register_setting(
'my_option_group', // Option group
'my_option_name', // Option name
array( $this, 'sanitize' ) // Sanitize
);
add_settings_section(
'setting_section_id', // ID
'My Custom Settings', // Title
array( $this, 'print_section_info' ), // Callback
'my-setting-admin' // Page
);
add_settings_field(
'my_content', //This ID of the field you want to use wp_editor for
'Write Your Content Here',
array( $this, 'my_content_callback' ),
'my-setting-admin',
'setting_section_id'
);
}
/**
* Sanitize each setting field as needed
*
* #param array $input Contains all settings fields as array keys
*/
public function sanitize( $input )
{
$new_input = array();
if( isset( $input['my_content'] ) )
$new_input['my_content'] = wp_kses_post( $input['my_content'] );
return $new_input;
}
/**
* Print the Section text
*/
public function print_section_info()
{
print 'Enter your settings below:';
}
/**
* Get the settings option array and print one of its values
*/
public function my_content_callback()
{
$args = array (
'media_buttons' => false,
'textarea_rows' => '10',
'textarea_name' => 'my_option_name[my_content]'
);
$options = get_option('my_option_name');
wp_editor( $options['my_content'], 'my_content', $args );
}
}
if( is_admin() )
$my_settings_page = new MySettingsPage();

adding custom page template from plugin

I'm working on building my first plugin for wordpress and am needing it to dynamically add a custom page for a login screen among other things.
The only thing I've been able to find that's anywhere near what I'm needing is here: WP - Use file in plugin directory as custom Page Template? & Possible to add Custom Template Page in a WP plugin?, but they're still not quite what I'm looking for.
Here is the code that I currently have running in my plugin...
// Add callback to admin menu
add_action( 'template_redirect', 'uploadr_redirect' );
// Callback to add menu items
function uploadr_redirect() {
global $wp;
$plugindir = dirname( __FILE__ );
// A Specific Custom Post Type
if ( $wp->query_vars["post_type"] == 'uploadr' ) {
$templatefilename = 'custom-uploadr.php';
if ( file_exists( TEMPLATEPATH . '/' . $templatefilename )) {
$return_template = TEMPLATEPATH . '/' . $templatefilename;
} else {
$return_template = $plugindir . '/themefiles/' . $templatefilename;
}
do_theme_redirect( $return_template );
}
}
function do_theme_redirect( $url ) {
global $post, $wp_query;
if ( have_posts ()) {
include( $url );
die();
} else {
$wp_query->is_404 = true;
}
}
Using this would require that my client create new page... what I'm needing is for the pluging to auto create a custom page (with a customized path, meaning .com/custompathhere) using a template file from the plugin folder, which will then contain all actions the plugin performs.
Note: This plugin is designed to run on one page, therefore reducing load-time and etc.
Thanks in advance!
Here is my code solution for adding page templates from a Wordpress plugin (inspired by Tom McFarlin).
This is designed for a plugin (the template files are searched for in the root directory of the plugin). These files are also in exactly the same format as if they were to be included directly in a theme. This can be changed if desired - check out my full tutorial http://www.wpexplorer.com/wordpress-page-templates-plugin/ for greater detail on this solution.
To customise, simply edit the following code block within the __construct method;
$this->templates = array(
'goodtobebad-template.php' => 'It\'s Good to Be Bad',
);
Full code;
class PageTemplater {
/**
* A Unique Identifier
*/
protected $plugin_slug;
/**
* A reference to an instance of this class.
*/
private static $instance;
/**
* The array of templates that this plugin tracks.
*/
protected $templates;
/**
* Returns an instance of this class.
*/
public static function get_instance() {
if( null == self::$instance ) {
self::$instance = new PageTemplater();
}
return self::$instance;
}
/**
* Initializes the plugin by setting filters and administration functions.
*/
private function __construct() {
$this->templates = array();
// Add a filter to the attributes metabox to inject template into the cache.
add_filter(
'page_attributes_dropdown_pages_args',
array( $this, 'register_project_templates' )
);
// Add a filter to the save post to inject out template into the page cache
add_filter(
'wp_insert_post_data',
array( $this, 'register_project_templates' )
);
// Add a filter to the template include to determine if the page has our
// template assigned and return it's path
add_filter(
'template_include',
array( $this, 'view_project_template')
);
// Add your templates to this array.
$this->templates = array(
'goodtobebad-template.php' => 'It\'s Good to Be Bad',
);
}
/**
* Adds our template to the pages cache in order to trick WordPress
* into thinking the template file exists where it doens't really exist.
*
*/
public function register_project_templates( $atts ) {
// Create the key used for the themes cache
$cache_key = 'page_templates-' . md5( get_theme_root() . '/' . get_stylesheet() );
// Retrieve the cache list.
// If it doesn't exist, or it's empty prepare an array
$templates = wp_get_theme()->get_page_templates();
if ( empty( $templates ) ) {
$templates = array();
}
// New cache, therefore remove the old one
wp_cache_delete( $cache_key , 'themes');
// Now add our template to the list of templates by merging our templates
// with the existing templates array from the cache.
$templates = array_merge( $templates, $this->templates );
// Add the modified cache to allow WordPress to pick it up for listing
// available templates
wp_cache_add( $cache_key, $templates, 'themes', 1800 );
return $atts;
}
/**
* Checks if the template is assigned to the page
*/
public function view_project_template( $template ) {
global $post;
if (!isset($this->templates[get_post_meta(
$post->ID, '_wp_page_template', true
)] ) ) {
return $template;
}
$file = plugin_dir_path(__FILE__). get_post_meta(
$post->ID, '_wp_page_template', true
);
// Just to be safe, we check if the file exist first
if( file_exists( $file ) ) {
return $file;
}
else { echo $file; }
return $template;
}
}
add_action( 'plugins_loaded', array( 'PageTemplater', 'get_instance' ) );
Check out my tutorial on this for more info.
http://www.wpexplorer.com/wordpress-page-templates-plugin/
I hope this helps you in what you want to do :)
I actually was able to talk to a developer friend of mine after revising the code quite a bit.
Here it is...
<?php
register_activation_hook( __FILE__, 'create_uploadr_page' );
function create_uploadr_page() {
$post_id = -1;
// Setup custom vars
$author_id = 1;
$slug = 'event-photo-uploader';
$title = 'Event Photo Uploader';
// Check if page exists, if not create it
if ( null == get_page_by_title( $title )) {
$uploader_page = array(
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => $author_id,
'post_name' => $slug,
'post_title' => $title,
'post_status' => 'publish',
'post_type' => 'page'
);
$post_id = wp_insert_post( $uploader_page );
if ( !$post_id ) {
wp_die( 'Error creating template page' );
} else {
update_post_meta( $post_id, '_wp_page_template', 'custom-uploadr.php' );
}
} // end check if
}
add_action( 'template_include', 'uploadr_redirect' );
function uploadr_redirect( $template ) {
$plugindir = dirname( __FILE__ );
if ( is_page_template( 'custom-uploadr.php' )) {
$template = $plugindir . '/templates/custom-uploadr.php';
}
return $template;
}
?>
I'm providing a general solution for those that want to add a template to a post from the their plugin. Use the single_template filter.
<?php
add_filter( 'single_template', 'add_custom_single_template', 99 );
function add_custom_single_template( $template ) {
return plugin_dir_path( __FILE__ ) . 'path-to-page-template-inside-plugin.php';
}
?>
Also, if you want to use the template in a specific post type, then:
<?php
add_filter( 'single_template', 'add_custom_single_template', 99 );
function add_custom_single_template( $template ) {
if ( get_post_type() == 'post-type-name'; ) {
return plugin_dir_path( __FILE__ ) . 'path-to-page-template-inside-plugin.php';
}
return $template;
}
?>

Override a function with child themes functions.php

As the title reads I'm trying to modify a function called by a parent theme in my child, I know that the child theme is set to be loaded beforehand so I'm curious if this is even possible?
My parent theme has a function called ajax_search_box() that I'd like to modify a query in, and I'd rather not modify the parent theme files in case I need to update it down the road.. what would be the best way to do this?
Also, for bonus points, how would I go about doing this with a widget as well? Thanks in advance!
function SearchFilter($query) {
// If 's' request variable is set but empty
if (isset($_GET['s']) && empty($_GET['s']) && $query->is_main_query()){
$query->is_search = true;
$query->is_home = false;
}
return $query;
}
add_filter('pre_get_posts','SearchFilter');
function ajax_search_box() {
if (isset($_GET["q"]))
{
$q = $_GET["q"];
global $wpdb;
$q = mysql_real_escape_string($q);
$q = $wpdb->escape($q);
$query = array(
'post_status' => 'publish',
'order' => 'DESC',
's' => $q
);
$get_posts = new WP_Query;
$posts = $get_posts->query( $query );
// Check if any posts were found.
if ( ! $get_posts->post_count )
die();
//Create an array with the results
foreach ( $posts as $post )
echo $post->post_title . "|" . $post->ID . "\n";
}
die();
}
// creating Ajax call for WordPress
add_action( 'wp_ajax_nopriv_ajax_search_box', 'ajax_search_box' );
add_action( 'wp_ajax_ajax_search_box', 'ajax_search_box' );
the parent theme needs to check if(function_exists('ajax_search_box')) and if it doesn't exist then it will declare it.
If the parent theme checks to see if the function exists, then you can declare it first and have it do what you want.
If the parent theme does not check, get in touch with the theme author to see if they will throw that change in for the next update....and code it yourself too. That way when the theme updates then you will still be good to go.
Break free of functions.php, write your own plugin.
<?php
/**
* Plugin Name: Manipulate the Parent
* Requires: PHP5.3+
*/
add_action( 'after_setup_theme', function()
{
remove_filter( 'pre_get_posts','SearchFilter' );
// now add your own filter
add_filter( 'pre_get_posts', 'your_callback_for_your_filter' );
});
function your_callback_for_your_filter()
{
// do stuff
}

WP - Use file in plugin directory as custom Page Template?

Is it possible for a file in the plugin directory to be used as a custom Page Template?
Also, how do you make a plugin create a page?
I'm developing a plugin for a client based on a theme, he wants this plugin to make sales pages while being able to use his theme on the homepage. This is a product that I'm making for him to market so it needs to be automated all through the plugin.
Is this possible?
EDIT
I have the activation/deactivation hooks in my plugins main file, and it's not working. Here's the code:
$filename = __FILE__;
register_activation_hook($filename, 'superActivation');
register_deactivation_hook($filename, 'superDeactivation');
global $myFile; global $fh; global $stringData; global $filename;
$myFile = "testFile.txt";
$stringData = "Testing\n";
$fh = fopen($myFile, 'w') or die("can't open file");
function superActivation() {
global $myFile; global $fh; global $stringData; global $filename;
fwrite($fh, $stringData);
fclose($fh);
}
function superDeactivation() {
$myFile = "testFile.txt";
unlink($myFile);
}
You can do this with the template_redirect hook. Here's my code to manually replace the template for a custom post type with one in the theme if there isn't one in the template folder. Put this in your plugin file and then put a folder underneath your plugin called themefiles with your default theme files.
//Template fallback
add_action("template_redirect", 'my_theme_redirect');
function my_theme_redirect() {
global $wp;
$plugindir = dirname( __FILE__ );
//A Specific Custom Post Type
if ($wp->query_vars["post_type"] == 'product') {
$templatefilename = 'single-product.php';
if (file_exists(TEMPLATEPATH . '/' . $templatefilename)) {
$return_template = TEMPLATEPATH . '/' . $templatefilename;
} else {
$return_template = $plugindir . '/themefiles/' . $templatefilename;
}
do_theme_redirect($return_template);
//A Custom Taxonomy Page
} elseif ($wp->query_vars["taxonomy"] == 'product_categories') {
$templatefilename = 'taxonomy-product_categories.php';
if (file_exists(TEMPLATEPATH . '/' . $templatefilename)) {
$return_template = TEMPLATEPATH . '/' . $templatefilename;
} else {
$return_template = $plugindir . '/themefiles/' . $templatefilename;
}
do_theme_redirect($return_template);
//A Simple Page
} elseif ($wp->query_vars["pagename"] == 'somepagename') {
$templatefilename = 'page-somepagename.php';
if (file_exists(TEMPLATEPATH . '/' . $templatefilename)) {
$return_template = TEMPLATEPATH . '/' . $templatefilename;
} else {
$return_template = $plugindir . '/themefiles/' . $templatefilename;
}
do_theme_redirect($return_template);
}
}
function do_theme_redirect($url) {
global $post, $wp_query;
if (have_posts()) {
include($url);
die();
} else {
$wp_query->is_404 = true;
}
}
You CAN add page templates from a plugin very easily by manipulating the page cache.
To customise, simply edit the following code block within the __construct method;
$this->templates = array(
'goodtobebad-template.php' => 'It\'s Good to Be Bad',
);
This is designed for a plugin (the template files are searched for in the root directory of the plugin). This can be changed if desired - check out my full tutorial http://www.wpexplorer.com/wordpress-page-templates-plugin/ for greater detail on this solution. These files are also in exactly the same format as if they were to be included directly in a theme.
Full code;
class PageTemplater {
/**
* A Unique Identifier
*/
protected $plugin_slug;
/**
* A reference to an instance of this class.
*/
private static $instance;
/**
* The array of templates that this plugin tracks.
*/
protected $templates;
/**
* Returns an instance of this class.
*/
public static function get_instance() {
if( null == self::$instance ) {
self::$instance = new PageTemplater();
}
return self::$instance;
}
/**
* Initializes the plugin by setting filters and administration functions.
*/
private function __construct() {
$this->templates = array();
// Add a filter to the attributes metabox to inject template into the cache.
add_filter(
'page_attributes_dropdown_pages_args',
array( $this, 'register_project_templates' )
);
// Add a filter to the save post to inject out template into the page cache
add_filter(
'wp_insert_post_data',
array( $this, 'register_project_templates' )
);
// Add a filter to the template include to determine if the page has our
// template assigned and return it's path
add_filter(
'template_include',
array( $this, 'view_project_template')
);
// Add your templates to this array.
$this->templates = array(
'goodtobebad-template.php' => 'It\'s Good to Be Bad',
);
}
/**
* Adds our template to the pages cache in order to trick WordPress
* into thinking the template file exists where it doens't really exist.
*
*/
public function register_project_templates( $atts ) {
// Create the key used for the themes cache
$cache_key = 'page_templates-' . md5( get_theme_root() . '/' . get_stylesheet() );
// Retrieve the cache list.
// If it doesn't exist, or it's empty prepare an array
$templates = wp_get_theme()->get_page_templates();
if ( empty( $templates ) ) {
$templates = array();
}
// New cache, therefore remove the old one
wp_cache_delete( $cache_key , 'themes');
// Now add our template to the list of templates by merging our templates
// with the existing templates array from the cache.
$templates = array_merge( $templates, $this->templates );
// Add the modified cache to allow WordPress to pick it up for listing
// available templates
wp_cache_add( $cache_key, $templates, 'themes', 1800 );
return $atts;
}
/**
* Checks if the template is assigned to the page
*/
public function view_project_template( $template ) {
global $post;
if (!isset($this->templates[get_post_meta(
$post->ID, '_wp_page_template', true
)] ) ) {
return $template;
}
$file = plugin_dir_path(__FILE__). get_post_meta(
$post->ID, '_wp_page_template', true
);
// Just to be safe, we check if the file exist first
if( file_exists( $file ) ) {
return $file;
}
else { echo $file; }
return $template;
}
}
add_action( 'plugins_loaded', array( 'PageTemplater', 'get_instance' ) );
Check out my tutorial on this for more info.
http://www.wpexplorer.com/wordpress-page-templates-plugin/
I hope this helps you in what you want to do :)
the code david posted above almost works for me. but it seems to blanket over all posts and pages for me. This code below works great for adding a template to a single post type that is created by my main plugin file
function get_book_post_type_template($single_template) {
global $post;
if ($post->post_type == 'books') {
$single_template = dirname( __FILE__ ) . '/themefiles/single-books.php';
}
return $single_template;
}
add_filter( "single_template", "get_book_post_type_template" ) ;
but I'm having trouble getting it to work with a custom page templates that don't have a post_type or has a post_type = page for instance lets say the custom page is an auxiliary member login page to see my custom posts. in my case this file is called myaccount.php and i've included it in a subfolder within my plugin folder named themefiles.
//Add Page and Post Template Files to Current Theme
add_action("template_redirect", 'my_account_redirect');
function my_account_redirect() {
global $wp;
//Set myAccount Custom Page Template
if (isset($wp->query_vars['pagename'] ) == "myaccount") {
$templatefilename = 'myAccount.php';
if (file_exists(dirname( __FILE__ ) . '/themefiles/' . $templatefilename)) {
$return_template = dirname( __FILE__ ) . '/themefiles/' . $templatefilename;
}
do_account_redirect($return_template);
}
}
//Finishing setting templates
function do_account_redirect($url) {
global $post, $wp_query;
if (have_posts()) {
include($url);
die();
} else {
$wp_query->is_404 = true;
}
}
when i do the above code the myaccount template shows up on all pages except for home which i believe is because it is set to a blogroll instead of a static page
I cannot reply to user1912899, but their recommendation seems to be the most elegant solution. To use a custom template to override single-post.php, I've implemented the following code. This will work for any custom single-****.php file you add to your plugin. If it doesn't exist, it just falls back to what WordPress normally uses.
add_action('template_include', 'my_template_include');
function my_template_include($template) {
$file = dirname( __FILE__ ).'/theme/single-'.get_post_type().'.php';
if(file_exists($file)) {
$template = $file;
}
return $template;
}

Resources