Programmatically embed a child post in Wordpress

I need to programmatically create a message (or page) for each Wordpress message created or updated by the user through the dashboard. I added a hook

add_action( 'publish_post', 'create_details_page'); 

An auto message is created only if the user creates or updates a message in a certain category, and an automatic post is created in another category. Each post belongs to only one category. Create a message 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 incompatible: sometimes I get one automatic post, sometimes two, and sometimes not. Why and how to embed a message exactly once?

To get an automatic post as a child of a user-created message:

 $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 results in no child messages at all. Without the category parameter, child messages are returned, and they have a category property. However, it seems that the complete list is not retrieved, and the results range from run to run.

If the contents of the automatic message are then edited from the control panel, this edited post is not returned by the above request. Why?

Any suggestions on how to resolve inconsistent behavior and make it work? I am new to Wordpress, and the online help is sparse and mainly intended for the dashboard user.

Using Wordpress 3.0.4, php5.

+4
source share
1 answer

Check the documentation - get_posts () takes a category argument, which is the category identifier. The category_name argument is used for another function, query_posts() .

To find the category identifier, hover over the link to it in the WP categories backend.

0
source

Source: https://habr.com/ru/post/1339123/


All Articles