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:

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

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 ); 
  • It's more performant to just pass the ID from JavaScript, using url_to_postid requires querying the database. – Milo Feb 5 '15 at 18:27
  • 2
    That's right, but if you want to do it only server side, like in my case where I have to validate the post id. – Sayed Taqui Feb 5 '15 at 18:30

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:

    action: 'new_item_save',
    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'];

Your Answer

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

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