WordPress – Change sub / child page theme automatically / programmatically


This is a situation that some times, we need to change the page template  under a parent page. For example, change theme of  all  child pages under the Page “Smart Phone” into some particular page theme. If there more 25 Pages under that particular parent, then it would be a tedious work to do in the GUI / Admin panel of WordPress. In such cases, you can use a handy code as below to change the page theme programmatically.

Use the following code snippet into function.php of your WordPress and make necessary changes

/* Code Snippet to change the page theme */

function switch_page_template_asyouneed() {
global $post;
$ancestors = $post->ancestors;
$parent_page_template = get_post_meta(end($ancestors),’_wp_page_template’,true);
$current_page_template=get_page_template_slug( $post->ID );
$change_template=TEMPLATEPATH . “/.$parent_page_template”;

if ( “some_condition_that_you_need”) {

load_template( $change_template);

}

}
add_action(‘template_redirect’,’switch_page_template_marine’);

 

WordPress  code snippet that you may find useful

empty( $post->post_parent ) ? get_the_title( $post->ID ) : get_the_title( $post->post_parent ); // get ID or name of the parent page

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s