下面是一个示例代码,可以帮助您入门-基本上它会拦截用户提交的帖子插件创建的新帖子(至少它会尝试,但一般来说,在该请求期间不应该创建任何其他帖子)。如果已经存在具有该名称的帖子,我们会将内容作为评论添加到该帖子,并重定向到该评论的URL,否则所有其他内容都由插件本身决定。
// Hook to the "wp_insert_post_empty_content" filter, since that is the only place
// we can intercept the creation of a new post and not let it be created
add_filter( \'wp_insert_post_empty_content\', \'intercept_user_submitted_post\', 10, 2 );
function intercept_user_submitted_post( $maybe_empty, $post_data ) {
if ( isset( $_POST[\'user-submitted-post\'] ) && ! empty( $_POST[\'user-submitted-post\'] ) ) {
$target_post = get_page_by_title( $post_data[\'post_title\'], OBJECT, \'post\' );
// We found an existing post!
if ( $target_post && $target_post->ID ) {
global $usp_options;
if ( stripslashes( $_POST[\'user-submitted-name\'] ) && ! empty( $_POST[\'user-submitted-name\'] ) ) {
$author_submit = stripslashes( $_POST[\'user-submitted-name\'] );
$author_info = get_user_by( \'login\', $author_submit );
if ( $author_info ) {
$authorID = $author_info->ID;
$authorName = $author_submit;
$authorEmail = $author_info->user_email;
} else {
$authorID = $usp_options[\'author\'];
$authorName = $author_submit;
$user_data = get_userdata( intval( $authorID ) );
$authorEmail = \'\';
}
} else {
$authorID = $usp_options[\'author\'];
$authorName = get_the_author_meta( \'display_name\', $authorID );
$user_data = get_userdata( intval( $authorID ) );
$authorEmail = $user_data->user_email;
}
$authorUrl = stripslashes( $_POST[\'user-submitted-url\'] );
$time = current_time(\'mysql\');
$data = array(
\'comment_post_ID\' => $target_post->ID,
\'comment_author\' => $authorName,
\'comment_author_email\' => $authorEmail,
\'comment_author_url\' => $authorUrl,
\'comment_content\' => $post_data[\'post_content\'],
\'comment_type\' => \'\',
\'comment_parent\' => 0,
\'user_id\' => $authorID,
\'comment_author_IP\' => preg_replace( \'/[^0-9a-fA-F:., ]/\', \'\',$_SERVER[\'REMOTE_ADDR\'] ),
\'comment_agent\' => isset( $_SERVER[\'HTTP_USER_AGENT\'] ) ? substr( $_SERVER[\'HTTP_USER_AGENT\'], 0, 254 ) : \'\',
\'comment_date\' => $time,
\'comment_approved\' => 1,
);
$comment_id = wp_insert_comment( $data );
// Redirect to the comment URL
wp_redirect( get_comment_link( $comment_id ) );
exit;
}
}
return $maybe_empty;
}
将该代码放在主题的函数中。php,应该就这些了。
PS:该代码还有更大的改进空间,比如在用户被重定向时显示消息,或者在评论中添加照片,但我将由您决定。我认为上面的代码是一个很好的起点。