I need to programmatically create a post (or page) for each WordPress post created or updated by a user via the dashboard. I added a hook
add_action( 'publish_post', 'create_details_page');
An auto post is created only if the user creates or updates a post in a certain category, and the auto post is created in a different category. Each post belongs to just one category.
Create the post as follows:
$auto_post = array(
'comment_status' => 'closed',
'post_category' => array($category->term_id),
'post_author' => $latest_post[0]->post_author,
'post_type' => 'post',
'post_title' => 'Details for ' . $latest_post[0]->post_title,
'post_parent' => $latest_post[0]->ID,
'post_content' => 'Post content'
);
$auto_post_id = wp_insert_post ( $auto_post, true );
$details = get_post( $auto_post_id );
wp_publish_post( $auto_post_id );
The results are inconsistent: sometimes I get one auto post created, sometimes two, and occasionally none. Why, and how to insert post exactly once?
To retrieve the auto post as a child of the user-created post:
$args = array(
'post_type' => 'post',
'post_parent' => $parent_post_id,
'post_status' => 'publish'
/* 'category_name' => array('Auto Post Category') */
);
$children = get_posts( $args );
Adding the category_name parameter causes to retrieve no child posts at all. Without the category parameter, child posts are returned, and they have the category set property. However, it seems like not a full list is retrieved, and results vary from run to run.
If the content of an auto post is then edited from the dashboard, this edited post is not returned by the above query. Why?
Any suggestions on how to resolve the inconsistent behavior and get this working?
I am new to WordPress, and online help is sparse and mostly aimed to the dashboard user.
Using WordPress 3.0.4, php5.
Check the documentation – get_posts() takes an argument of
category
, which is the category ID. Thecategory_name
argument is used on a different function,query_posts()
.To find the category ID, hover over the link to it on the WP categories backend.