Set the default Parent Page and Template in Wordpress using php

Tags: Wordpress.

On a Wordpress site I have users who need to add content to a particular section of the site and nowhere else. To make editing as simple as possible, I want to set the Parent page and Template automatically when users with a certain role are adding a new page. Add these two functions to your theme's functions.php file.

Set the Parent page

/**
 * Set the default Parent page
 */
add_filter( 'wp_insert_post_data', 'set_default_page_parent' );
function set_default_page_parent( $data ) {
  if ( $data['post_status'] == 'auto-draft' && $data['post_type'] == 'page' ) {
    $user = wp_get_current_user();
    // The user role to match
    if ( in_array( 'newsletter editor', (array) $user->roles ) ) {
      // Set the ID for the parent page
      $data['post_parent'] = 232;
    }
  }
  return $data;
}

Set the Template

/**
 * Set the default Template
 */
function set_default_page_template() {
    global $post;
    if ( $post->post_status == 'auto-draft' && $post->post_type == 'page' ) {
      $user = wp_get_current_user();
      // The user role to match
      if ( in_array( 'newsletter editor', (array) $user->roles ) ) {
        // Select the template to use
        $post->page_template = "templates/template-newsletter.php";
      }
    }
}
add_action('add_meta_boxes', 'set_default_page_template');