需要将其编写为函数来创建插件,并使用模板页面中插件的操作挂钩
function my_frontend_custom_post( $new_post ) {
<?php if ( isset( $_POST[\'submitted\'] ) && isset( $_POST[\'new_post_nonce_field\'] ) && wp_verify_nonce( $_POST[\'new_post_nonce_field\'], \'new_post_nonce_action\' ) ) {
if ( trim( $_POST[\'post-title\'] ) === \'\' ) {
$postingError .= \'Please insert a title. \';
$hasError = true;
} else {
$postTitle = trim( $_POST[\'post-title\'] );
}
$new_post = array( array(
\'post_content\' => $_POST[\'post-content\'],
\'post_title\' => wp_strip_all_tags( $_POST[\'post-title\'] ),
\'post_status\' => \'publish\',
\'post_type\' => \'cpt\',
);
if ( !$hasError == true ) {
$post_id = wp_insert_post( $new_post );
wp_set_object_terms( $post_id, $_POST[\'post-categ\'], \'categories\' );
if ( $post_id ) {
wp_safe_redirect( home_url() );
echo \'Succes\';
exit;
} // end - check if post\'s created and redirect to home_url
} //end - if free of error insert_post and set_object categories
} // end - first if wrapper
} // end - function
add_action( \'wp_insert_post\', \'my_frontend_custom_post\', 10, 1 );
显示表单:
function display_frontend_form() {
<form id="new_post" method="POST" action="" enctype="multipart/form-data">
<label for="post-title">The Title</label>
<input id="post-title" name="post-title" type="text" />
<label for="post-content">The Content</label>
<textarea id="post-content" name="post-content"></textarea>
<label for="post-categ">The Categories</label>
<input id="post-categ" name="post-categ" type="text" />
<?php wp_nonce_field( \'new_post_nonce_action\', \'new_post_nonce_field\' ); ?>
<button type="submit">Publish</button>
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
}
add_action( \'show_form\', \'display_frontend_form\' );
然后在模板页面中,使用动作挂钩来实现奇迹:
do_action( \'show_form\' );