How to add a custom-post-type post within another custom-post-type post edit screen using AJAX?

I’ve got two custom post types: CD and Track. Each of them has got some metadata associated with them.

What I’m trying to do is to add Track posts to a CD post when the CD post is being edited. On the CD edit page I have “Add Track” link. When clicking on it, I would like a “New Track Form” to appear under the link that will ask for a Track (custom-post-type) information, along with all metadata that needs to be specified for a Track – as if “Add Track” link was clicked from the left WP menus. Hope that makes sense.CD

Read More

My CD and Track custom-post-types are registered as following: http://wordpress.pastebin.com/Y6aagTVs

On the edit CD page I have the following link <a class="addTrack" href="">Add Track</a>

I’m missing AJAX and the function that will handle the addition of the “New Track form”. Here is what I’ve got so far in the AJAX function:

// Add Tracks   
$("a.addTrack").click(function () {
    opts = {
        url: ajaxurl, // ajaxurl is defined by WordPress and points to /wp-admin/admin-ajax.php
        type: 'POST',
        async: true,
        cache: false,
        dataType: 'json',
        data:{
            action: 'track_add', // Tell WordPress how to handle this ajax request
        },
        success: function(response) {
            return false;
        },
        error: function(xhr,textStatus,e) {  // This can be expanded to provide more information
            alert("There was an error adding a track.");
            return false;
        }
    };
    $.ajax(opts);
});

And the function that will handle the insertion of the “New Track Form” is

// Add Tracks
add_action('wp_ajax_track_add', 'my_ajax_admin_add_track');
function my_ajax_admin_add_track() {
}

I don’t know how to go on about the AJAX and my_ajax_admin_add_track() functions. Would really appreciate any help and tips!!!

Many thanks,
Dasha

Related posts

Leave a Reply

1 comment

  1. For your my_ajax_admin_add_track() function, grab the form field data from the $_POST array, populate the required data in an array to call wp_insert_post(), then call wp_insert_post() passing it the post data. It should return the new post ID number if successful.