I’m trying to create a set of buttons on wordpress Page post types that allow the end user to create a new page that is a sibling (same parent page) or a child page of the current page.
In order to do so, i’m creating a link post-new.php and populating the parameter parent_id in the URL.
In my functions.php, I’ve hooked wp_insert_post … the problem I have now is how to actually set the post_parent on the $post object … I dont see any WordPress functions to do so; I’ve tried using wp_update_post … but this doesnt seem to work for me … here’s the code in my functions.php:
add_action('wp_insert_post','grey_templater_set_post_parent',10,2);
function grey_templater_set_post_parent($postid,$post) {
if ( ! $parentid = grey_get_post_parent_by_url()
or 'auto-draft' !== $post->post_status )
return;
$mypage = array();
$mypage['ID'] = $postid;
$mypage['post_parent'] = $parentid;
wp_update_post( $mypage );
}
function grey_get_post_parent_by_url() {
if (! isset( $_GET['parent_id'] ) )
return FALSE;
return array_map('sanitize_title', explode(',', $_GET['parent_id']));
}
From the Codex:
To set your post parent, pass
'post_parent' => <parent_id>
as part of the array that you pass towp_update_post
. That part should be right as far as I can tell, but as you say does not seem to work. But read on.What you are doing creates an infinite Loop when I try it, though, since
wp_update_post
usedwp_insert_post
. You hook gets called over and over until the site runs out of memory. I suspect that that is part of the problem here. That can be fixed with this:What you are also doing, potentially, is setting the post parent on a revision. You need to compensate.
But that still doesn’t work. I am not sure why (I’d be happy if someone could tell me though), but I am skipping over that because this is not the hook I’d use. Even if this worked you’d have two database writes, and you only need one. There is a hook called
wp_insert_post_data
that runs before the post is inserted/updated at all.That does work, assuming your
grey_get_post_parent_by_url()
function works.