functions.php with wp_redirect($url); exit(); make

2019-07-25 12:11发布

I'm creating a form for the users to submit posts from the front end. Once the form is submitted the users should be redirected to the post they have just created.

I have this code in my functions.php. However it makes my website blank...

I think it's related to the exit() line, I've tried to modify it but it doesn't work, nothing happens at all. It just shows a white page.

  <?php 
    wp_register_script( 'validation', 'http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js', array( 'jquery' ) );
    wp_enqueue_script( 'validation' );


    $post_information = array(
        'post_title' => wp_strip_all_tags( $_POST['postTitle'] ),
        'post_content' => $_POST['postContent'],
        'post_type' => 'post',
        'post_status' => 'publish'
    );

    $post_id = wp_insert_post($post_information);
    $url = get_permalink( $post_id );
    wp_redirect($url);
    exit();

    ?>

Do you have any ideas? How can I fix that? Thanks!

1条回答
Viruses.
2楼-- · 2019-07-25 12:39

OK, it won't work like that. First of all, you shouldn't add scripts like that when the functions.php is loaded (because it's loaded much too early, before WP has actually decided what to do with the request that comes from the browser) - use the wp_enqueue_scripts for that:

<?php
function add_my_scripts() {
    wp_register_script( 'validation', 'http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js', array( 'jquery' ) );
    wp_enqueue_script( 'validation' );
}
add_action( 'wp_enqueue_scripts', "add_my_scripts");
?>

Your creation of a new post runs on every request - even for that request when your browser wants to show that new post.

Depending on what exactly you need, you might want to put this into an action hook as well, but it should help already if you check that it was actually a POST request that contains a postTitle, something like this:

<?php
if( $_SERVER["REQUEST_METHOD"] == "POST" && array_key_exists("postTitle", $_POST)) {
    $post_information = array(
        'post_title' => wp_strip_all_tags( $_POST['postTitle'] ),
        'post_content' => $_POST['postContent'],
        'post_type' => 'post',
        'post_status' => 'publish'
    );

    $post_id = wp_insert_post($post_information);
    if(is_wp_error($post_id)) {
        print "An error occured :(\n";
        var_export($post_id);
    }
    else {
            $url = get_permalink( $post_id );
            wp_redirect($url);
    }
    exit();
}
?>
查看更多
登录 后发表回答