Skip to content

Instantly share code, notes, and snippets.

@sagarjadhav
Created April 22, 2016 06:49
Show Gist options
  • Save sagarjadhav/aa9277b689aa8b492fe586074dc09ba5 to your computer and use it in GitHub Desktop.
Save sagarjadhav/aa9277b689aa8b492fe586074dc09ba5 to your computer and use it in GitHub Desktop.
<?php
// Define custom post type string
define( 'CUSTOM_POST_TYPE', 'affiliates' );
/**
* Register the meta box
*/
if ( !function_exists( 'page_templates_dropdown_metabox' ) ) {
function page_templates_dropdown_metabox() {
add_meta_box( CUSTOM_POST_TYPE . '-page-template', __( 'Template', 'TEXTDOMAIN' ), 'render_page_template_dropdown_metabox', CUSTOM_POST_TYPE, 'side', 'low' );
}
add_action( 'add_meta_boxes', 'page_templates_dropdown_metabox' );
}
/**
* Render your metabox - This code is similar to what is rendered on the page post type
* @return void
*/
if ( !function_exists( 'render_page_template_dropdown_metabox' ) ) {
function render_page_template_dropdown_metabox() {
global $post;
$template = get_post_meta( $post->ID, '_wp_page_template', true );
echo "<label class='screen-reader-text' for='page_template'>Page Template</label>
<select name='_wp_page_template' id='page_template'>
<option value='default'>Default Template</option>";
page_template_dropdown( $template );
echo "</select>";
}
}
/**
* Save the page template
* @return void
*/
if ( !function_exists( 'save_page_template' ) ) {
function save_page_template( $post_id ) {
// Skip the auto saves
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
} elseif ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
return;
} elseif ( defined( 'DOING_CRON' ) && DOING_CRON ) {
return;
}
// Only update the page template meta if we are on our specific post type
elseif ( CUSTOM_POST_TYPE === $_POST[ 'post_type' ] ) {
update_post_meta( $post_id, '_wp_page_template', esc_attr( $_POST[ '_wp_page_template' ] ) );
}
}
add_action( 'save_post', 'save_page_template' );
}
/**
* Set the page template
* @param string $template The determined template from the WordPress brain
* @return string $template Full path to predefined or custom page template
*/
if ( !function_exists( 'set_page_template' ) ) {
function set_page_template( $template ) {
global $post;
if ( CUSTOM_POST_TYPE === $post->post_type ) {
$custom_template = get_post_meta( $post->ID, '_wp_page_template', true );
// since our dropdown only gives the basename, use the locate_template() function to easily find the full path
if ( $custom_template && 'default' != $custom_template ) {
return locate_template( $custom_template );
}
}
return $template;
}
add_filter( 'single_template', 'set_page_template' );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment