简体   繁体   中英

Wordpress - Add form inside post edit page

I would like to create a new metabox in the post edit page which contains a single button which should submit a form with hidden fields.

The problem is that the post edit page is a form itself - so technically I am trying to create a form inside a form and this is not possible by HTML specification.

Also, I don't want to submit it via GET (simple link) because it must not get cached.

This is the code:

function meta_box_html()
{
    ?>
    <form action="..." method="post">
        <input type="hidden" name="name" value="value">
        <input type="submit">
    </form>
    <?php
}

add_action("add_meta_boxes", function () {
    add_meta_box("id", "title", "meta_box_html", "post", "side", "high", null);
});

When I click the button - nothing happens and the page is just reloaded.

Any ideas how to add a form to post edit page?

I had the same issue. Here's how I solved it.

First, for convenience, I generated my form in an admin alert, as below. This could be dropped in an if() that checks whether the current page's ID is 'post' and parent_file is 'edit.php' if you only want this to appear on the "Edit Post" page.

function myform_custom_box_html($post)
{
    ?>
    <div id="myform_holder">
     <form action="<?php echo admin_url('admin-post.php'); ?>" method="post" id="myform" >
        <input type="hidden" name="action" value="myform">
        <input id="myform_fname" type="text" name="myform_fname" value="" placeholder="Recipient name" /><br />
        <input type="submit" name="myform_submit" id="rejecter_submit" class="button button-primary" value="Submit Form">
    </form>
    </div>
    <?php
}

add_action( 'admin_notices', 'myform_custom_box_html' );

Then I used a bit of js to move it to the place I wanted to in the page. in this case, it appends it just below the 'publish' button but you could target any element in the DOM you want. You'll have to put this in a file that's properly enqueued to the wordpress admin:

$(document).ready(function() {
  var myform =  $('#myform_holder').remove();
  myform.appendTo('#major-publishing-actions');
});

Both forms work correctly with this approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM