[英]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.我使用添加到购物车 Ajax 回调,但我想念如何在那里获取帖子 ID。 MY GOAL: I want to use the add_filter only on a specific page.我的目标:我只想在特定页面上使用 add_filter。
PHP in functions.php在functions.php中的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).这是行不通的,因为$post
是 NULL(因为 Ajax woocommerce_add_cart_item_data 钩子)。
So I tried the following code in the JS to get the post id in JS (working).所以我在JS中尝试了以下代码来获取JS中的帖子ID(工作)。
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?现在,我如何将 id 移交给我的 Ajax 回调以使用它?
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).为此,我使用了第三方插件,它为我提供了所需产品的按钮,所以我没有使用默认的$product
或$post
对象(就像在单个产品页面中一样)。
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.