How to conditionally check a custom single post template in WordPress - wordpress

I am using the following function to call a custom single post overriding the default one single.php
function call_different_single_post($single_template)
{
global $post;
$path = get_stylesheet_directory() . '/includes/templates' . '/';
$single_template = $path. 'single-1.php';
return $single_template;
}
add_filter('single_template', 'call_different_single_post');
It's calling the single-1.php template for the single posts.
Now I want to check this template conditionally so that I can call some other js files like
function call_cust_js_single(){
if( /*..this is single-1.php template..*/){
wp_register_script('cust-js', get_stylesheet_directory_uri() . 'custom.js', false, '1.0.0');
wp_enqueue_script('cust-js');
}
}
add_action('wp_enqueue_scripts', 'call_cust_js_single');

There's a post similar to this but it doesn't quite cover your request. Here's the link here
Here's the valuable code:
add_filter( 'template_include', 'var_template_include', 1000 );
function var_template_include( $t ){
$GLOBALS['current_theme_template'] = basename($t);
return $t;
}
function get_current_template( $echo = false ) {
if( !isset( $GLOBALS['current_theme_template'] ) )
return false;
if( $echo )
echo $GLOBALS['current_theme_template'];
else
return $GLOBALS['current_theme_template'];
}
Now you have the function get_current_template that will return the filename of the template file.
Now edit your header.php file, here's an example:
<?php if('single-1.php' == get_current_template())
{
//load your scripts here
} ?>
It's not as clean as what you were looking for but I think it will help you.

Related

Not getting the content of template made in plugin

I have created a template in my plugin with the help of this code
function ldc_add_thanku_page_template ($templates) {
$templates['thanku.php'] = 'Thanku Template';
return $templates;
}
function ldc_redirect_thanku_page_template ($template) {
if ('thanku.php' == basename ($template))
$template = PLUGIN_PATH .'templates/public/thanku.php';
return $template;
}
But when i am assigning this template to any page I am not getting the content inside it. For now i have added a very simple code, can anyone please help me with this.
<?php
/* Template Name: Thanku Template */
echo "<h1>Hello</h1>";
?>
Your Code will not work on the latest WordPress version, This code will work below 4.7
Try This
function ldc_add_thanku_page_template ($templates) {
$templates['thanku.php'] = 'Thanku Template';
return $templates;
}
function ldc_redirect_thanku_page_template ($template) {
$post = get_post();
$page_template = get_post_meta( $post->ID, '_wp_page_template', true );
if ('thanku.php' == basename ($page_template))
$template = WP_PLUGIN_DIR .'/mypluginname/thanku.php';
return $template;
}

Wordpress - First check page.php in plugin

Is it possible to make WordPress look at plugin directory first and if the system finds that page, for example, page.php, archive.php, single.php... show layout from plugin files and don't look at theme files?
Absolutely! Take a look at the single_template and archive_template filters. They're relatively straight forward to use:
function get_custom_post_type_template($single_template) {
global $post;
if ($post->post_type == 'my_post_type') {
$single_template = dirname( __FILE__ ) . '/post-type-template.php';
}
return $single_template;
}
add_filter( 'single_template', 'get_custom_post_type_template' );
There's also This Section on effectively adding single-post_type.php to the Template Hierarchy, but I prefer a slightly modified version that is IMO easier to read:
add_filter( 'single_template', 'my_single_templates' );
function my_single_templates( $single_template ){
global $post;
$file = '/my/path/to/templates/dir/'. $post->post_type .'/single-'. $post->post_type .'php';
if( file_exists( $file ) )
$single_template = $file;
return $single_template;
}

Wordpress Plugin Custom Post Type Archive Template results in other pages not displaying

This is the code I am using to call my archive template, now the knowledgebase section works, the forums work, but all other pages throughout the website are now blank.
function kb_archive_template_function($arhive_template){
if(is_post_type_archive('knowledgebase')){
$theme_files = array('/templates/archive-knowledgebase.php');
$exists_in_theme = locate_template($theme_files, false);
if($exists_in_theme == ''){
return plugin_dir_path(__FILE__) . '/templates/archive-knowledgebase.php';
}
return $archive_template;
}
}
You can use this code ,instead of your code
function get_custom_post_type_template( $archive_template ) {
global $post;
if ( is_post_type_archive ( 'knowledgebase' ) ) {
$archive_template = plugin_dir_path(__FILE__) . '/templates/archive-knowledgebase.php';
}
return $archive_template;
}
add_filter( 'archive_template', 'get_custom_post_type_template' ) ;
Try that, then let me know the result. Thanks

target a custom page using plugin function in wordpress

i created a custom page named custom_page.php in wordpress and use this as a page template.
i wanted to create my own functions and only target my custom_page.php. this function will be installed as a plugin.
what kind of WP HOOKS should i use, for example i have this code below
function your_function() {
if ( is_page_template('custom_page.php') ) {
echo '<p>This is inserted at the bottom</p>';
{
}
add_action('wp_footer', 'your_function');
i want to only execute this code in my custom_page.php footer area.
[EDIT]
You can use these hooks for page templates.
http://adambrown.info/p/wp_hooks/hook/page_template
Or may be something like this...
add_filter( 'page_template', 'check_the_template' );
function check_the_template( $template ) {
if( 'custom_page.php' == basename( $template ) ) {
// do some things here by calling functions, hooks etc..
}
return $template;
}
If you want to just echo "Hello World" :
add_filter( 'page_template', 'check_the_template' );
function check_the_template( $template ) {
if( 'pagetemplete.php' == basename( $template ) ) {
add_action( 'the_content', 'echofunction' );
}
return $template;
}
function echofunction() {
echo "Hello World";
}

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