每当创建或编辑事件时,我都会尝试将某些字段从事件自定义文章类型复制到标准博客文章中。我现在让它工作到当事件更新或编辑时它将创建一个博客文章,但如果我要添加一个全新的事件,它会在添加包含内容的正确文章之前添加 2 篇博客文章。它创建的第一个帖子是自动草稿,然后创建一个带有标题和作者但没有内容的帖子。不过,它创建的第 3 个帖子是正确的。如何防止它在我添加新活动时创建这些额外的帖子?
这是我到目前为止的代码:
function create_event_post( $post_id ) {
// If this is just a revision, don't create a new post.
if ( wp_is_post_revision( $post_id ) )
return;
// Set the title, thumbnail id, author, and content variables
$post_title = get_the_title( $post_id );
$post_type = get_post_type($post_id);
$post_content = get_post_field('post_content', $post_id);
$thumbnail_id = get_post_thumbnail_id( $post_id );
$author_id = get_post_field ('post_author', $post_id);
$author_name = get_the_author_meta( 'display_name' , $author_id );
// Set the variables for the new post to the same as the event post
$new_post = array(
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => $author_id,
'post_title' => $post_title,
'post_content' => $post_content,
'post_status' => 'publish',
'post_type' => 'post'
);
// If the post is not "tribe_events", don't create a new post.
if ( "tribe_events" != $post_type )
return;
// Create the new post and retrieve the id of the new post
$new_post_id = wp_insert_post ( $new_post );
// Set the featured image for the new post to the same image as event post
set_post_thumbnail( $new_post_id, $thumbnail_id );
}
add_action( 'save_post', 'create_event_post' );
让它工作了。如果有人想看看它是如何工作的,这是最终代码。
add_action( 'save_post', 'create_event_post' );
function create_event_post( $post_id ) {
// Set the title, thumbnail id, author, and content variables
$post_title = get_the_title( $post_id );
$post_type = get_post_type($post_id);
$post_content = get_post_field('post_content', $post_id);
$thumbnail_id = get_post_thumbnail_id( $post_id );
$author_id = get_post_field ('post_author', $post_id);
// If the post is not "tribe_events", don't create a new post.
if ( "tribe_events" != $post_type )
return;
$new_post = array(
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => $author_id,
'post_title' => $post_title,
'post_content' => $post_content,
'post_status' => 'publish',
'post_type' => 'post'
);
remove_action( 'save_post', 'create_event_post' );
$post_exists = get_page_by_title( $post_title, $output, "post" );
if ( !empty($post_exists) ) {
// Update post
$update_post = array(
'ID' => $post_exists->ID,
'post_title' => $post_title,
'post_content' => $post_content,
);
// Update the post into the database
wp_update_post( $update_post );
set_post_thumbnail( $post_exists->ID, $thumbnail_id );
}
else {
// Create the new post and retrieve the id of the new post
$new_post_id = wp_insert_post ( $new_post );
// Set the featured image for the new post to the same image as event post
set_post_thumbnail( $new_post_id, $thumbnail_id );
}
// Now hook the action
add_action( 'save_post', 'create_event_post' );
}