简体   繁体   中英

How to get post id in Ajax callback in Wordpress

I use the Add to cart Ajax callback, but I miss how I can get the post Id there. MY GOAL: I want to use the add_filter only on a specific page.

PHP in functions.php

add_filter( 'woocommerce_add_cart_item_data', 'iconic_add_engraving_text_to_cart_item' , 10, 3 );

function iconic_add_engraving_text_to_cart_item( $cart_item_data, $product_id, $variation_id ) {
    global $post;
    if ( $post->ID === 54214 )  {
        $engraving_text = 'test';
        $cart_item_data['iconic-engraving'] = $engraving_text;
        return $cart_item_data; 
    } else {
        return $cart_item_data; 
    }
}

This is NOT WORKING because $post is NULL (because of the Ajax woocommerce_add_cart_item_data hook).

So I tried the following code in the JS to get the post id in JS (working).

function get_current_page_id() {
    var page_body = $('body.page');

    var id = 0;

    if(page_body) {
        var classList = page_body.attr('class').split(/\s+/);

        $.each(classList, function(index, item) {
            if (item.indexOf('page-id') >= 0) {
                var item_arr = item.split('-');
                id =  item_arr[item_arr.length -1];
                return false;
            }
        });
    }
    return id;
}

Now, how can I handover the id to my Ajax Callback to work with it?

Any advice?


EDIT:

I forgot to tell that I am planning to use the add to cart action on other pages but not a single product page.

For that, I am using a third party plugin which gives me the button for my desired product, so I am not using default $product or $post Object (like in single product pages).

I have finally found a solution for this "simple" problem. I can work with a session:

add_action( 'wp_head', 'set_session' );
add_filter( 'woocommerce_add_cart_item_data', 'iconic_add_engraving_text_to_cart_item' , 10, 3 );

function set_session()  {
    session_start();
    // add post id
    global $post;
    $post_id = $post->ID;
    $_SESSION['post_id'] = $post_id; 
}

function iconic_add_engraving_text_to_cart_item( $cart_item_data, $product_id, $variation_id ) {
        session_start();
        if( $_SESSION['post_id'] == 54214 ) {
            $engraving_text = 'test';
            $cart_item_data['iconic-engraving'] = $engraving_text;
            return $cart_item_data;
        } else {
            return $cart_item_data;
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM