Skip to content

Instantly share code, notes, and snippets.

@akshuvo
Created January 10, 2021 12:01
Show Gist options
  • Save akshuvo/0f279f1920fc74044126f7f73d6f12c5 to your computer and use it in GitHub Desktop.
Save akshuvo/0f279f1920fc74044126f7f73d6f12c5 to your computer and use it in GitHub Desktop.
Load custom page templates from plugin for custom post type
<?php
function wpse255804_add_page_template ($templates) {
$templates['custom-template-1'] = 'Custom Template 1';
$templates['custom-template-2'] = 'Custom Template 2';
$templates['custom-template-3'] = 'Custom Template 3';
return $templates;
}
add_filter ('theme_tourfic_templates', 'wpse255804_add_page_template');
// Single Template
function tourfic_single_page_template( $single_template ) {
global $post;
$page_template = get_post_meta( $post->ID, '_wp_page_template', true );
if ( 'tourfic' === $post->post_type && 'custom-template-1' == basename ($page_template) ) {
$theme_files = array('single-tourfic.php', 'templates/single-tourfic-1.php');
$exists_in_theme = locate_template($theme_files, false);
if ( $exists_in_theme != '' ) {
return $exists_in_theme;
} else {
return dirname( __FILE__ ) . '/templates/single-tourfic-1.php';
}
} elseif ( 'tourfic' === $post->post_type && 'custom-template-2' == basename ($page_template) ) {
$theme_files = array('single-tourfic.php', 'templates/single-tourfic-2.php');
$exists_in_theme = locate_template($theme_files, false);
if ( $exists_in_theme != '' ) {
return $exists_in_theme;
} else {
return dirname( __FILE__ ) . '/templates/single-tourfic-2.php';
}
} elseif ( 'tourfic' === $post->post_type && 'custom-template-3' == basename ($page_template) ) {
$theme_files = array('single-tourfic.php', 'templates/single-tourfic-3.php');
$exists_in_theme = locate_template($theme_files, false);
if ( $exists_in_theme != '' ) {
return $exists_in_theme;
} else {
return dirname( __FILE__ ) . '/templates/single-tourfic-3.php';
}
} elseif ( 'tourfic' === $post->post_type ) {
$theme_files = array('single-tourfic.php', 'templates/single-tourfic.php');
$exists_in_theme = locate_template($theme_files, false);
if ( $exists_in_theme != '' ) {
return $exists_in_theme;
} else {
return dirname( __FILE__ ) . '/templates/single-tourfic.php';
}
}
return $single_template;
}
add_filter( 'single_template', 'tourfic_single_page_template');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment