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' );

2 Answers
2

Its an old question however would like to answer for other people

Within ajax function hooked to wp_ajax do this.

$url     = wp_get_referer();
$post_id = url_to_postid( $url ); 

Leave a Reply

Your email address will not be published. Required fields are marked *