Skip to content

Instantly share code, notes, and snippets.

@rianrietveld
Last active August 29, 2015 14:23
Show Gist options
  • Save rianrietveld/928e113ad29581a5bff8 to your computer and use it in GitHub Desktop.
Save rianrietveld/928e113ad29581a5bff8 to your computer and use it in GitHub Desktop.
Assign a template to a single custom post type page
<?php
// set custom post type templates in post meta
add_action('publish_name_cpt', 'prefix_add_template', 10, 2 );
function prefix_add_template( $post_id, $post ) {
if ( $post_id == 1234 ) {
add_post_meta( $post_id, '_wp_page_template', 'your-template.php', true );
}
}
// use template in front end
add_filter( 'single_template','prefix_get_template', 10, 1 );
function prefix_get_template( $template ) {
global $wp_query;
$post = $wp_query->get_queried_object();
if ( $post->ID == 1234 ) {
$post_template = get_post_meta( $post->ID, '_wp_page_template', true );
if ( !empty ( $post_template ) && $post_template != 'default' ) {
$template = get_stylesheet_directory() . "/" . $post_template;
}
}
return $template;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment