WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

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'];
share|improve this answer

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 ); 
share|improve this answer
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
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

Your Answer


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.