Warning: Please do not give out any FTP or ssh credentials to anyone, unless you trust them completely. Giving out login details is dangerous.
If the asker does not get an answer then they have 10 days to request a refund.
$5
How to assign a page template automatically from function
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!
This question has been answered.
beowulf | 09/15/11 at 7:24am
Edit
Previous versions of this question:
09/15/11 at 7:29am
(2) Possible Answers Submitted...
See a chronological view of answers?
Warning: Please do not give out any FTP or ssh credentials to anyone, unless you trust them completely. Giving out login details is dangerous.
-

Last edited:
09/15/11
7:35amPeter Michael says:
function template_redirect_to_winning_page()
{
global $wp;
if( $wp->query_vars["pagename"] == "winning" ) {
include(TEMPLATEPATH . '/template-full-width.php');
die();
}
}
add_action ('template_redirect', 'template_redirect_to_winning_page');
-

Last edited:
09/15/11
7:38amJurre Hanema says: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.- 09/15/11 7:44am
beowulf says: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.
- 09/15/11 7:44am
This question has expired.
beowulf voted on this question.
Current status of this question: Completed
Warning: Please do not give out any FTP or ssh credentials to anyone, unless you trust them completely. Giving out login details is dangerous.
If the asker does not get an answer then they have 10 days to request a refund.
