WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to change my page template automatically when someone selects a specific post parent.

I have the code to update the template but couldn't find anything for detection of post parent attribute changes. Can you help?

share|improve this question
You mean... when someone changes the page parent in page editor (inside wp-admin)? – Krzysiek Dróżdż Jun 28 '13 at 10:56
Check this and the signaled duplicate. – brasofilo Jun 29 '13 at 14:20

This is how you do it...

function update_post_template($post_id, $post){

    //set $post_parent_id however you wish  

    if ($post->post_parent == $post_parent_id) {

        //unhook save_post action to avoid infinite loop
        remove_action('save_post', 'update_post_template'); 

        //change template
        update_post_meta( $post_id, '_wp_page_template', 'custom_template.php' );

        //re-hook save_post action
        add_action('save_post', 'update_post_template');


add_action('save_post', 'update_post_template', 10, 2);


To explain what is happening, first we hook onto the save_post action which is fired when inserting/updating a post. We then check for the existence of a certain post_parent id which is up to you to decide and determine which (you may want to extend this conditional statement to cover multiple cases). If we find a match, we unhook the save_post action to avoid creating an infinite loop when we call our update_post_meta function. Once the page template has been updated, we re-hook the save_post action and continue on our merry way.

share|improve this answer

Using MySQL you can do;

$result= $wpdb->get_row("select post_parent from wp_posts where ID=".$post->ID);

     //your logic
     //Do something else
share|improve this answer
I don't think it is answer for this question, or I misunderstood something. Nevetheless I'm pretty sure you should not write your SQL queries like that. Don't use hardcoded wp_posts (it depends on WP config). You should escape $post->ID in your query (you don't know what will be hidden in this value, and assuming it's always correct isn't very good idea). – Krzysiek Dróżdż Jun 28 '13 at 12:22

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.