I created a PHP function that will automatically create a new WordPress post based on content added onto a page. However, it just stays on the current page but I want it to go to that new created post. How could I redirect so that it goes to that post? Here’s what I have so far:
<?php if(isset($_POST['submitButton'])) { $storyTitle=$_POST['storyTitle']; $storyCategory=wp_strip_all_tags( $_POST['storyCategory'] ); $storyTags=$_POST['storyTags']; switch ($storyCategory) { case "Action": $storyCategory='3'; break; case "Adventure": $storyCategory='4'; break; case "Comedy": $storyCategory='5'; break; case "Fanfiction": $storyCategory='6'; break; case "Fantasy": $storyCategory='9'; break; case "General Fiction": $storyCategory='12'; break; case "Horror": $storyCategory='13'; break; case "Mystery": $storyCategory='8'; break; case "Poetry": $storyCategory='14'; break; case "Romance": $storyCategory='7'; break; case "Science Fiction": $storyCategory='10'; break; case "Short Story": $storyCategory='11'; break; default: $storyCategory=$_POST['storyCategory']; } $my_post = array( 'post_type' => 'post', 'post_title' => wp_strip_all_tags( $_POST['storyTitle'] ), 'post_content' => '', 'post_status' => 'publish', 'post_author' => 1, 'post_category' => explode(',', $storyCategory), 'tags_input' => explode(',', $storyTags) ); if( null == get_page_by_title( $title ) ) { $post_id=wp_insert_post($my_post); //wp_redirect( site_url()."?post=".$post_id); } } ?>
Advertisement
Answer
You can use get_permalink
to get post url. check below code.
<?php if(isset($_POST['submitButton'])) { $storyTitle=$_POST['storyTitle']; $storyCategory=wp_strip_all_tags( $_POST['storyCategory'] ); $storyTags=$_POST['storyTags']; switch ($storyCategory) { case "Action": $storyCategory='3'; break; case "Adventure": $storyCategory='4'; break; case "Comedy": $storyCategory='5'; break; case "Fanfiction": $storyCategory='6'; break; case "Fantasy": $storyCategory='9'; break; case "General Fiction": $storyCategory='12'; break; case "Horror": $storyCategory='13'; break; case "Mystery": $storyCategory='8'; break; case "Poetry": $storyCategory='14'; break; case "Romance": $storyCategory='7'; break; case "Science Fiction": $storyCategory='10'; break; case "Short Story": $storyCategory='11'; break; default: $storyCategory=$_POST['storyCategory']; } $my_post = array( 'post_type' => 'post', 'post_title' => wp_strip_all_tags( $_POST['storyTitle'] ), 'post_content' => '', 'post_status' => 'publish', 'post_author' => 1, 'post_category' => explode(',', $storyCategory), 'tags_input' => explode(',', $storyTags) ); if( null == get_page_by_title( $title ) ) { $post_id = wp_insert_post($my_post); if( $post_id ){ wp_redirect( get_permalink( $post_id ) ); exit; } } } ?>