Code based in Bainternet's answer to this question: Make Categories and Tags required in admin
See code comments.
add_action( 'admin_head-post-new.php', 'wpse_59770_publish_admin_hook' );
add_action( 'admin_head-post.php', 'wpse_59770_publish_admin_hook' );
add_action( 'wp_ajax_wpse_59770_pre_submit_validation', 'wpse_59770_ajax_pre_submit_validation' );
function wpse_59770_publish_admin_hook()
{
global $current_screen;
if( 'page' != $current_screen->post_type )
return;
?>
<script language="javascript" type="text/javascript">
jQuery(document).ready(function() {
jQuery('#publish').click(function()
{
var form_data = jQuery('#parent_id').val();
form_data = ( '' != form_data ) ? '1' : '0';
var data = {
action: 'wpse_59770_pre_submit_validation',
security: '<?php echo wp_create_nonce( 'pre_publish_validation' ); ?>',
form_data: form_data
};
jQuery.post(ajaxurl, data, function(response)
{
// OK, save page
if (response=='true') {
jQuery('#ajax-loading').hide();
jQuery('#publish').removeClass('button-primary-disabled');
jQuery('#post').submit();
}
// Not OK, display alert message
else
{
alert(response);
jQuery('#ajax-loading').hide();
jQuery('#publish').removeClass('button-primary-disabled');
return false;
}
});
return false;
});
});
</script>
<?php
}
function wpse_59770_ajax_pre_submit_validation()
{
//simple Security check
check_ajax_referer( 'pre_publish_validation', 'security' );
// Parent is set, no further action
if( '1' == $_POST['form_data'] )
{
echo 'true';
die();
}
$args = array( 'post_type' => 'page', 'post_parent'=> 0, 'numberposts' => -1 );
$parents_total = get_posts( $args );
// Total parents is less than 9, no further action
if( count($parents_total) < 9 )
{
echo 'true';
die();
}
// No more parents allowed
else
{
$error = "No more Parent Pages allowed";
echo $error;
die();
}
}