I am trying to develop a plugin to extend WooCommerce and I would like to do something with the product id when I land on a single product page (e.g. store it in the database or store it in a session variable).
However whatever hook I try to use, two results are given. So for example I might use the hook woocommerce_single_product_summary as follows:
add_action( 'woocommerce_single_product_summary', 'do_my_thing' );
function do_my_thing() {
global $post;
store_the_id( $post->ID ); //some function to do something with the id
}
When a user lands on a product page, the hook is fired twice, the function store_my_id runs twice and with two different post ids. The first is the correct id for the product in questions, and the second is an id for some other product.
This occurs whatever hook I use e.g. get_header. It wouldn't be a problem if I just wanted to echo something to the page because the echo only outputs when the hook fires for the first time.
Can anyone explain to me what is happening here? Is this supposed to be happening? And if so is there some way I can differentiate between the two ids returned to know which is actually the id for the product I have just landed on?
I have tried this on a completely fresh Wordpress install with just the WooCommerce plugin installed, the twentyfifteen theme and 2 products added so I don't think it's being caused by anything custom I am doing.
Any help really appreciated...
EDIT
I wondered whether using get_queried_object would help (as per below) but the same thing happens
add_action( 'woocommerce_single_product_summary', 'do_my_thing' );
function do_my_thing() {
$queried_object = get_queried_object();
if ( $queried_object->post_type == 'product' ) {
store_the_id( $queried_object->ID ); //some function to do something with the id
}
}