John Davidson

php - Why WooCoomerce add a hooked element twice?

0 comments
Message:


I created a snipped to display custom content when a specific variation from a subscription is in cart. This works perfectly fine! But I have some problems with the selected hook. I want to display it on the checkout page. And it adds it twice! But I don't know why.. why is that hook fired 2 times?


Here is a screenshot: https://ibb.co/dQf8tsZ


This is my code - (When I use another hook it only displays it once.)


add_action( 'woocommerce_review_order_before_shipping', 'check_if_variation_is_in_cart', 10, 0 );

function check_if_variation_is_in_cart() {

$variable_product_id = 15340;

if( in_array( $variable_product_id, array_column( WC()->cart->get_cart(), 'product_id' ) ) ) {

echo '<div class="cbc-abo-monthly">';
echo '<h3 class="cbc-abo-monthly-header">' . __( 'Info', 'woocommerce' ) . ' </h3>';
echo '<p>' . __( 'This is a subscription', 'woocommerce' ) . ' </p>';
echo '</div>';

}

}


My Answer:
> I see that you are using the 'woocommerce_review_order_before_shipping' hook to display custom content on the checkout page. The reason why the content is being displayed twice is because the hook is being fired twice on the checkout page.

One possible solution is to check if the content has already been displayed before displaying it again. You can do this by setting a flag variable and checking its value before displaying the content.

Here is an updated version of your code with the flag variable implementation:

php
add_action( 'woocommerce_review_order_before_shipping', 'check_if_variation_is_in_cart', 10, 0 );

function check_if_variation_is_in_cart() {
$variable_product_id = 15340;

// Check if content has already been displayed
if ( ! get_option( 'variation_content_displayed' ) ) {
if( in_array( $variable_product_id, array_column( WC()->cart->get_cart(), 'product_id' ) ) ) {
echo 'Custom content here';
}

// Set flag to indicate content has been displayed
update_option( 'variation_content_displayed', true );
}
}


By using the flag variable 'variation_content_displayed', the custom content will only be displayed once on the checkout page. Make sure to reset the flag variable if needed, for example when the cart is updated or cleared.

Rate this post

4 of 5 based on 2839 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us