如何让用户通过提交帖子表单来创建帖子?

时间:2021-12-22 作者:PantelD

因此,我在主页上有以下简单的帖子表单:

<form action="/wp-content/plugins/myplugin/my_create_post.php" method="POST">
  <label for="title_given">Title:</label>
  <textarea id="title_given" name="title_given" rows="3" cols="100" maxlength="150"></textarea>
  <br>
  <input type="submit" value="Create Post">
</form>
“The”;my\\u create\\u帖子。php“;文件为:

<?php
if( $_POST[\'title_given\'] ) {
    // This echo successfully shows the title_given from the form
    echo "Title given is: " . $_POST[\'title_given\'] . "<br />";

    // Create post object
    $my_post = array(
      \'post_title\'    => wp_strip_all_tags( $_POST[\'title_given\'] ),
      \'post_content\'  => \'Did it work??\',
      \'post_status\'   => \'publish\',
      \'post_author\'   => 1,
      \'post_type\'     => \'post\'
    );

    // Insert the post into the database
    $return_value = wp_insert_post( $my_post, true );   
    
    // This echo never appears for some reason
    echo "wp_insert_post() returned: " . var_dump( $return_value ) . "<br />";

    exit();
}
?>
我以管理员的身份运行所有测试。单击“提交”按钮时,我看到一个白色页面,其中仅成功打印了第一个回显,控制台中出现以下错误:

enter image description here

从管理页面或mysql cli进行检查时,似乎从未创建任何帖子。理想情况下,应该将用户重定向到一个新帖子,该帖子的标题与他提交的标题相同。对我做错了什么有什么见解吗?或者如果有更好的方法来完成我的任务wp_insert_post()? 谢谢

1 个回复
SO网友:mhdi

这个echo 部分应该在代码的末尾。请记住,任何回音或打印都应该在代码的末尾。

<?php
    if( $_POST[\'title_given\'] ) {
        // Create post object
        $my_post = array(
          \'post_title\'    => wp_strip_all_tags( $_POST[\'title_given\'] ),
          \'post_content\'  => \'Did it work??\',
          \'post_status\'   => \'publish\',
          \'post_author\'   => 1,
          \'post_type\'     => \'post\'
        );
    
        // Insert the post into the database
        $return_value = wp_insert_post( $my_post, true );   
        
        // This echo never appears for some reason
        echo "Title given is: " . $_POST[\'title_given\'] . "<br />";
        echo "wp_insert_post() returned: " . var_dump( $return_value ) . "<br />";
   
    }