Skip to content

Instantly share code, notes, and snippets.

@lunule
Created December 27, 2024 20:29
Show Gist options
  • Select an option

  • Save lunule/06670cfd4364e63866b773685d8dc491 to your computer and use it in GitHub Desktop.

Select an option

Save lunule/06670cfd4364e63866b773685d8dc491 to your computer and use it in GitHub Desktop.
[WordPress - Programmatically Assign Page Template to CPT Posts] #wp #core #cpt #custom #post #types #page #templates
/**
* Attaches the specified template to the posts of the identified post type.
*
* @params $post_type The name of the post type to attach the template to.
* @params $template_path The template's filename (assumes .php' is specified)
*
* @returns empty array if the post type does not have posts; otherwise,
* the post id array of the updated posts.
*/
function attach_template_to_post_type( $post_type, $template_file_name ) {
$posts_args_Arr = array(
'post_type' => $post_type,
'posts_per_page' => -1,
);
$posts_Arr = get_posts($posts_args_Arr);
$updated_posts_Arr = [];
if ( 0 < count($posts_Arr) ) :
foreach ( $posts_Arr as $post ) : setup_postdata( $post );
if (
isset($post->ID) &&
is_numeric($post->ID) &&
0 < intval($post->ID)
) :
update_post_meta( $post->ID, '_wp_page_template', $template_file_name );
array_push($updated_posts_Arr, $post->ID);
endif;
endforeach;
wp_reset_postdata();
endif;
return $updated_posts_Arr;
}
// Usage - just put it in functions.php. You can't use hooks here since you need to
// use specific function parameters.
attach_template_to_post_type( 'mac-city-pages', 'page-landing.php' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment