【问题标题】:functions.php with wp_redirect($url); exit(); makes wordpress site blankfunctions.php 与 wp_redirect($url);出口();使 wordpress 网站空白
【发布时间】:2017-10-11 12:11:51
【问题描述】:

我正在为用户创建一个表单以从前端提交帖子。 提交表单后,用户应该被重定向到他们刚刚创建的帖子。

我的functions.php 中有这段代码。但是它使我的网站空白...

我认为它与 exit() 行有关,我试图修改它但它不起作用,根本没有任何反应。它只是显示一个白页。

  <?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();

    ?>

你有什么想法吗?我该如何解决?谢谢!

【问题讨论】:

  • 它只是在你的functions.php中,还是包装在一个函数中,该函数通过add_action或类似的东西添加到动作钩子中?
  • 我的functions.php里就是这样的..????

标签: php wordpress function url-redirection


【解决方案1】:

好的,它不会那样工作。 首先,您不应该在加载 functions.php 时添加这样的脚本(因为它加载得太早了,在 WP 实际决定如何处理来自浏览器的请求之前) - 为此使用 wp_enqueue_scripts :

<?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");
?>

您创建的新帖子会针对每个请求运行 - 即使您的浏览器想要显示该新帖子时的请求也是如此。

根据您的具体需要,您可能也希望将其放入操作挂钩中,但如果您检查它实际上是一个包含 postTitle 的 POST 请求,它应该已经有所帮助,如下所示:

<?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();
}
?>

【讨论】:

  • 太棒了!完美运行!感谢您的解释! :)
猜你喜欢
  • 2017-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多