Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I wrote a custom AJAX function in which I have assigned a post type to be a child of another post type. In one function I am looping through those child posts, and I want to update the database to reflect the post_parent(the post which the child posts belong to). Problem is, I cannot grab that post's ID from anywhere to update the db. Any suggestions?

Here is the jQuery function:

    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        async: true, 
                        cache: false,
                        dataType: 'json',
                        data:{
                                action: 'new_item_save',
                                item_order: $('#img-sortable').sortable('toArray').toString()

                        }
    });

And here is the PHP callback:

function save_new_img_order($post) {
global $wpdb;
$pid = $post->ID;

$order = explode(',', $_POST['item_order']);
$counter = 0;
foreach ($order as $item_id) {
    $wpdb->update($wpdb->posts, array( 'menu_order' => $counter, 'post_parent' => $pid ), array( 'ID' => $item_id ) );
    $counter++;
}
die(1);
}
add_action('wp_ajax_new_item_save', 'save_new_img_order');

Thanks in advance for any pointers!

share|improve this question
    
Please take a look at the wp-localize-script to see how to properly pass data from PHP to javascript. –  kaiser Jul 25 '12 at 12:25
add comment

1 Answer

The ajax hook won't pass back a $post object to your callback - how on earth would it know to do so!

You need to send the data yourself:

data:{
    action: 'new_item_save',
    post_id: POST_ID_EITHER_PARSED_FROM_DOM_OR_PHP_ECHOED,
    item_order: $('#img-sortable').sortable('toArray').toString()
}

...and then grab it from $_POST in your handler:

function save_new_img_order() {
    $post_id = $_POST['post_id'];
    ...
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.