Ask your WordPress questions! Pay money and get answers fast! (more info)

How to assign a page template automatically from function


Hi everyone!

I'm trying to create a function inside my theme's 'function.php' file which automatically assigns a template to a specific page.

For example, I have a page called 'Winning' and I want it to automatically be assigned the 'template-full-width.php' template file.

I'd like it to check if the 'Winning' page exists and, if so, update the page's template. Is that even possible?

I suspect I should be using the 'update_post_meta' function but I'm having trouble getting it to work. Something like:

$post_name = 'winning';
$post_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = $post_name");

update_post_meta($post_id, '_wp_page_template','template-full-width.php');

Any help would be appreciated!

Answers (2)


Jurre Hanema answers:

Your query is not entirely correct. Try this:

global $wpdb;

$post_name = 'winning';

$query = $wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE post_name = %s", $post_name);
$post_id = $wpdb->get_var($query);

update_post_meta($post_id, '_wp_page_template','template-full-width.php');

Altough I suspect there might be a better way to achieve what you want by simply using Wordpress's template hierarchy. If you create a template page-winning.php and the page's slug is winning, then WP will automatically use that template to display the page.

beowulf comments:

Thanks Jurre for helping me get on the right track! It does assign a full width template to my page now. :)

Under normal circumstances you're correct about creating a separate template for that page but I'm integrating a plugin that I'm trying not to modify directly (for future updates). Long story short, creating a function inside of the theme seems to be the best option for this particular situation.


Peter Michael answers:

function template_redirect_to_winning_page()
global $wp;
if( $wp->query_vars["pagename"] == "winning" ) {
include(TEMPLATEPATH . '/template-full-width.php');
add_action ('template_redirect', 'template_redirect_to_winning_page');