Skip to content

Instantly share code, notes, and snippets.

@wookiecooking
Created March 26, 2015 17:12
Show Gist options
  • Save wookiecooking/edba275a4269da3e5926 to your computer and use it in GitHub Desktop.
Save wookiecooking/edba275a4269da3e5926 to your computer and use it in GitHub Desktop.
template selection in custom post types in wordpress
<?php
function cptTemplateMetaBox() {
$post_types = get_post_types();
foreach ( $post_types as $post_type ) {
add_meta_box( 'cpt-template-meta-box', 'Template', 'cptTemplateMetaBoxMarkup', $post_type, 'side', 'high' );
}
}
add_action( 'add_meta_boxes', 'cptTemplateMetaBox' );
function cptTemplateMetaBoxMarkup( $post ) {
wp_nonce_field( basename(__FILE__), 'cpt_template_meta_nonce' );
$current_template = get_post_meta( $post->ID, 'cpt_page_template', true);
$template_options = get_page_templates();
$box_label = '<label for="cpt_page_template">Page Template</label>';
$box_select = '<select name="cpt_page_template">';
$box_default_option = '<option value="">Default Template</option>';
$box_options = '';
foreach ( $template_options as $name=>$file ) {
if ( $current_template == $file ) {
$box_options .= '<option value="' . $file . '" selected="selected">' . $name . '</option>';
} else {
$box_options .= '<option value="' . $file . '">' . $name . '</option>';
}
}
echo $box_label;
echo $box_select;
echo $box_default_option;
echo $box_options;
echo '</select>';
}
function cptTemplateMetaBoxSave( $post_id ) {
$current_nonce = $_POST['cpt_template_meta_nonce'];
$is_autosaving = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$valid_nonce = ( isset( $current_nonce ) && wp_verify_nonce( $current_nonce, basename( __FILE__ ) ) ) ? 'true' : 'false';
if ( $is_autosaving || $is_revision || !$valid_nonce ) {
return;
}
$cpt_page_template = $_POST['cpt_page_template'];
update_post_meta( $post_id, 'cpt_page_template', $cpt_page_template );
}
add_action( 'save_post', 'cptTemplateMetaBoxSave' );
function loadCptPostTemplate() {
$query_object = get_queried_object();
$page_template = get_post_meta( $query_object->ID, 'cpt_page_template', true );
$my_post_type = get_post_type($query_object->ID);
$default_templates = array();
$default_templates[] = 'single-{$object->post_type}-{$object->post_name}.php';
$default_templates[] = 'single-{$object->post_type}.php';
$default_templates[] = 'single.php';
if ( $query_object->post_type == $my_post_type ) {
// if the page_template isn't empty, set it as the default_template
if ( !empty( $page_template ) ) {
$default_templates = $page_template;
}
}
$new_template = locate_template( $default_templates, false );
return $new_template;
}
add_filter( 'single_template', 'loadCptPostTemplate' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment