Given a classic course-lesson structure, created by custom post types, I want to add a new empty lesson for a course, by using a simple html form on a metabox, in the course edit screen.

I think I understand the basis for execute a function in response to a GET (or POST) action on a html form, and indeed the new lesson is created if I build the proper URL on the browser address bar, or if I put the html form in a template page. But when I move the same html form to the metabox and push the submit button, I just get a redirection to the post list admin page, and the function for create a new lesson is not executed.

Any clue about what is going wrong?

I'm learning, and I'm writting this code on a code snippet, using Code Snippets plugin (I think it is equivalent to write the code to the functions.php file of the theme).

Thank you very much!

// Add metabox to "bdg_course" CPT
add_action('add_meta_boxes', function() { 
   add_meta_box('bdg_add_lesson', 'Add lesson', 'bdg_new_empty_lesson_form', 
'bdg_course', 'side');

// Callback function to fill metabox with html form
function bdg_new_empty_lesson_form() { 
<form action="<?php echo esc_url( admin_url('admin-post.php') ); ?>" 
    <input type="hidden" name="action" value="foobar">
    <input type="text" name="title" id="title" value="">
    <input type="submit" value="submit">

// Let's use admin_post_foobar hook to execute a form handler function every 
// time somebody sends the form
add_action('admin_post_foobar', 'programmatically_create_lesson');

// Form handler function
function programmatically_create_lesson() {
            'post_title'        =>  $_GET["title"],               
            'post_type'         =>  'bdg_lesson'
  • when you are on the edition page of a post, all metaboxes are already inside a tag "form". then you cannot output another form, having nested forms is not allowed by HTML. another solution for the lesson creation can be the use of an AJAX call. – mmm Jul 14 '18 at 14:17
  • Ok, thank you for pointing it out, mmm. That was why it was not working as I expected. – Injaki Jul 15 '18 at 14:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.